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

时间:2016-06-05 18:36:13

标签: 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));
    }
}

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

1 个答案:

答案 0 :(得分:2)

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

我尝试了这种方式并且确实有效:

查看codebehind:

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>