ContainerContentChanging是初始化渲染,UpdateLayout用来保证元素已经渲染,而不是重新渲染整个列表。
根据您的情况,我建议使用IValueConverter 进行背景颜色转换。您可以将Index 属性添加到数据类型以识别它现在的位置。
这是一个简单的例子:
TestModel.cs
public class TestIndex:INotifyPropertyChanged
{
private int _index;
public int Index
{
get => _index;
set
{
_index = value;
OnPropertyChanged();
}
}
// other properties
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
converter.cs
public class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if(value is int index)
{
// You can change color here.
if (index % 2 == 0)
return new SolidColorBrush(Colors.Red);
else
return new SolidColorBrush(Colors.Blue);
}
return new SolidColorBrush(Colors.Red);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
xaml
<Page ...>
<Page.Resources>
<local:BackgroundConverter x:Key="BackgroundConverter"/>
<DataTemplate x:Key="DefaultRow" x:DataType="local:TestIndex">
<Grid Background="{x:Bind Index,Converter={StaticResource BackgroundConverter}, Mode=OneWay}" Height="50">
</Grid>
</DataTemplate>
</Page.Resources>
<Grid>
<ListView ItemsSource="{x:Bind TestCollection}"
IsItemClickEnabled="True"
AllowDrop="True"
CanReorderItems="True"
IsSwipeEnabled="True"
ItemTemplate="{StaticResource DefaultRow}"
>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</Page>
xaml.cs
private ObservableCollection<TestIndex> TestCollection = new ObservableCollection<TestIndex>();
public ListViewPage()
{
this.InitializeComponent();
for (int i = 0; i < 10; i++)
{
TestCollection.Add(new TestIndex()
{
Index = i
});
}
TestCollection.CollectionChanged += CollectionChanged;
}
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
for (int i = 0; i < TestCollection.Count; i++)
{
TestCollection[i].Index = i;
}
}
这是因为在 ListView 中拖放项目时不会触发 DragItemsCompleted 事件。因为本质上是对集合元素的删除和添加,所以需要为集合注册CollectionChanged事件。
最好的问候。