C# UWP ListView在拖放后更新行背景
我目前这样做是为了使我的C# UWP ListView在拖放后更新行背景,c#,listview,uwp,win-universal-app,C#,Listview,Uwp,Win Universal App,我目前这样做是为了使我的列表视图具有交替的行背景 private void SongsListView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { if (AlternatingRowColor) args.ItemContainer.Background = args.ItemIndex % 2 == 0 ?
列表视图
具有交替的行背景
private void SongsListView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
{
if (AlternatingRowColor)
args.ItemContainer.Background = args.ItemIndex % 2 == 0 ? Helper.WhiteSmokeBrush : Helper.WhiteBrush;
}
此外,我还允许我的ListView
能够拖放项目。但是,行颜色在删除后不会更新其颜色,即使我执行了以下操作:
private void SongsListView_DragItemsCompleted(ListViewBase sender, DragItemsCompletedEventArgs args)
{
sender.UpdateLayout(); // Refresh Row Color
}
这意味着我的列表视图在拖放后没有交替背景
如何更新其背景?ContainerContentChanging
是初始化呈现,而UpdateLayout
用于确保元素已呈现,而不是重新呈现整个列表
对于您的情况,我建议使用IValueConverter
进行背景色转换。您可以向数据类型添加索引
属性,以标识它现在所在的位置
这是一个简单的例子:
TestModel.cs
公共类TestIndex:INotifyPropertyChanged
{
私有整数指数;
公共整数索引
{
get=>\u索引;
设置
{
_指数=价值;
OnPropertyChanged();
}
}
//其他属性
公共事件属性更改事件处理程序属性更改;
公共void OnPropertyChanged([CallerMemberName]字符串propertyName=”“)
{
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName));
}
}
转换器.cs
public类BackgroundConverter:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、字符串语言)
{
if(值为int索引)
{
//你可以在这里换颜色。
如果(索引%2==0)
返回新的SolidColorBrush(颜色为红色);
其他的
返回新的SolidColorBrush(Colors.Blue);
}
返回新的SolidColorBrush(颜色为红色);
}
公共对象转换回(对象值、类型targetType、对象参数、字符串语言)
{
抛出新的NotImplementedException();
}
}
xaml
xaml.cs
private ObservableCollection TestCollection=new ObservableCollection();
公共列表视图页()
{
this.InitializeComponent();
对于(int i=0;i<10;i++)
{
添加(新的TestIndex()
{
指数=i
});
}
TestCollection.CollectionChanged+=CollectionChanged;
}
私有void CollectionChanged(对象发送方,NotifyCollectionChangedEventArgs e)
{
for(int i=0;i
这是因为在ListView中拖放项目时不会触发DragItemsCompleted
事件。因为它本质上是删除和添加集合元素,所以需要为集合注册CollectionChanged
事件
致以最诚挚的问候。一个更简单的解决方案是:
private void SongsListView_DragItemsCompleted(ListViewBase sender, DragItemsCompletedEventArgs args)
{
for(int i = 0; i < sender.Items.Count; i++)
{
var container = sender.ContainerFromIndex(i) as ListViewItem;
container.Background = i % 2 == 0 ? Helper.WhiteSmokeBrush : Helper.WhiteBrush;
}
}
private void SongsListView\u DragItemsCompleted(ListViewBase发送方,DragItemsCompletedEventArgs args args)
{
对于(int i=0;i