列表视图项目UWP的备用颜色

Res*_*Res 5 c# listview uwp uwp-xaml

我有一堂课,以替代项目的背景颜色,但是如果删除项目,则背景颜色不会更新。删除项目后是否可以刷新背景颜色?

备用颜色的代码。类列表视图:

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);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

代码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>
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Jus*_* XL 6

您只需要AlternatingRowListView稍微扩展一下已扩展的控件即可实现所需的功能。

您可以通过订阅的VectorChanged事件来监视何时将某个项目从列表中删除Items,然后您就可以(直观地)遍历删除项目下面的所有已实现项目,并相应地更改其背景颜色。

这样的事情会做-

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)