c# - 如何从自己的集合中自动更新 ItemsSource?

标签 c# xaml uwp uwp-xaml

我创建了自己的集合并实现了 INotifyCollectionChanged。

public class ObservableSortedSet<T> : SortedSet<T>, INotifyCollectionChanged
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public new bool Add(T item)
    {
        var result = base.Add(item);
        if (result)
            CollectionChanged?.Invoke(item,
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
        return result;
    }

    public new bool Remove(T item)
    {
        var result = base.Remove(item);
        if (result)
            CollectionChanged?.Invoke(item,
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
        return result;
    }

    public new void Clear()
    {
        base.Clear();
        CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

但是,当我尝试在 View 中使用此集合作为 ItemsSource 时,它​​们不会自动更新,例如删除一个项目。正如我在这里的其他问题中看到的,我应该实现 INotifyCollectionChanged。我这样做了,但它不起作用。有什么建议吗?

最佳答案

您的 remove 方法不起作用的原因是您必须添加已删除元素的索引。

我尝试了这种方法,确实有效:

查看隐藏代码:

public ObservableSortedSet<String> Values { get; private set; }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        Values = new ObservableSortedSet<string>();
        Values.Add("Test0");
        Values.Add("Test1");
        Values.Add("Test2");
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Values.Add("Test" + Values.Count);
    }
}

查看:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <ListView ItemsSource="{Binding Path=Values}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <Button Grid.Row="1" Content="Add" Click="Button_Click"/>
</Grid>

关于c# - 如何从自己的集合中自动更新 ItemsSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645422/

相关文章:

javascript - Webbrowser控件的onclick事件

c# - 从 XML 加载 WeifenLuo DockPanel Suite 布局

C# ListView 列宽自动

c# - 从独立存储加载的图像根本不具有约束力

c# - 未调用 WPF IValueConverter.ConvertBack

uwp - 在我的 UWP 应用中存储设置的简单方法

javascript - cordova uwp windows 10 应用程序的转发按钮?

C# Winforms : programatically display Button's Hover State

c# - PointerWheelChanged 事件 UWP

wpf - 显示非矩形文本 block