gpt4 book ai didi

c# - ListView 项 UWP 的替代颜色

转载 作者:太空狗 更新时间:2023-10-29 23:05:15 36 4
gpt4 key购买 nike

我有一个类可以对项目的背景进行颜色交替,但是如果我删除一个项目,背景颜色不会更新。有没有办法在删除项目后刷新背景颜色?

交替颜色的代码。类 ListView :

public class AlternatingRowListView : ListView
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var listViewItem = element as ListViewItem;
if (listViewItem != null)
{
var index = IndexFromContainer(element);

if (index % 2 == 0)
{
listViewItem.Background = new SolidColorBrush(Colors.LightBlue);
}
else
{
listViewItem.Background = new SolidColorBrush(Colors.Transparent);
}
}

}
}

代码 xaml:

<local:AlternatingRowListView x:Name="listview">
<ListViewItem>item 1</ListViewItem>
<ListViewItem>item 2</ListViewItem>
<ListViewItem>item 3</ListViewItem>
<ListViewItem>item 4</ListViewItem>
<local:AlternatingRowListView.ItemTemplate>
<DataTemplate>

</DataTemplate>
</local:AlternatingRowListView.ItemTemplate>
</local:AlternatingRowListView>

提前致谢。

最佳答案

您只需扩展您已经扩展的 AlternatingRowListView 控件一点即可实现您的需要。

您可以通过订阅 ItemsVectorChanged 事件来监视项目何时从列表中删除,然后您只需循环遍历所有 实现项目(视觉上)移除的项目并相应地改变它们的背景颜色。

像这样的东西会做-

public AlternatingRowListView()
{
DefaultStyleKey = typeof(ListView);

Items.VectorChanged += OnItemsVectorChanged;
}

private void OnItemsVectorChanged(IObservableVector<object> sender, IVectorChangedEventArgs args)
{
// When an item is removed from the list...
if (args.CollectionChange == CollectionChange.ItemRemoved)
{
var removedItemIndex = (int)args.Index;

// We don't really care about the items that are above the deleted one, so the starting index
// is the removed item's index.
for (var i = removedItemIndex; i < Items.Count; i++)
{
if (ContainerFromIndex(i) is ListViewItem listViewItem)
{
listViewItem.Background = i % 2 == 0 ?
new SolidColorBrush(Colors.LightBlue) : new SolidColorBrush(Colors.Transparent);
}
// If it's null, it means virtualization is on and starting from this index the container
// is not yet realized, so we can safely break the loop.
else
{
break;
}
}
}
}

关于c# - ListView 项 UWP 的替代颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130461/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com