【问题标题】:How to update ItemsSource automatically from own collection?如何从自己的集合中自动更新 ItemsSource?
【发布时间】:2016-06-06 03:14:57
【问题描述】:

我创建了自己的集合并实现了 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。我这样做了,但它不起作用。有什么建议吗?

【问题讨论】:

    标签: c# xaml uwp uwp-xaml


    【解决方案1】:

    你的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>
    

    【讨论】:

    • 您是否尝试删除某个项目?
    • 是的,当添加被删除元素的索引时,删除工作。
    • 我认为我应该将其添加到 CollectionChanged 的​​调用中。如何获取已删除项目的索引,或者我可以只使用 0?
    • 这就是问题:D
    • 还是不行,没关系,我会手动刷新我的 ItemsSources。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多