首页 > 解决方案 > 网格未更新

问题描述

我的 C#/WPF 应用程序中有以下代码。单击 Refrsh 按钮时,我在 Viewmodel 上调用 GetData 方法并尝试重置可观察集合。但是网格中的数据没有得到更新。我在这里做错了什么? CustomObservableCollection 类中的 Reset 方法逻辑是否正确?

谢谢你的帮助。

ViewModel.cs:

private object _myLock = new object();
internal void GetData()
        {
            var data = ...//Get data from database

            lock (_myLock)
            {
                if (MyCollection != null )
                {
                    MyCollection.Reset(data);

                }
                else
                {
                    MyCollection = new CustomObservableCollection<Product>(data);
                }
            }

XAML:

    <Grid >
<.... ItemsSource="{Binding MyCollection}" 
                                                        </Grid>

    <Button Click="RefreshGridButton_Click" Content="Refresh" />

CustomObservableCollection.cs

public class CustomObservableCollection<T> : ObservableCollection<T>
{
    private object _lock = new object();
    public CustomObservableCollection()
        : base()
    {
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);
    }

    public CustomObservableCollection(IEnumerable<T> collection)
        : base(collection)
    {
    }


    public void Reset(IEnumerable<T> range)
    {
        if (range == this)
        {
            return;
        }
        lock (_lock)
        {
            this.Items.Clear();

            foreach (var item in range)
          {
                this.Items.Add(item);
            }

            this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, range, 0));


        }


    }



}

标签: c#wpfobservablecollection

解决方案


尝试将您的 XAML 代码更改为以下代码 -

<... ItemsSource="{Binding Path=MyCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ... />

实际上,我认为重新初始化 ObservableCollection 而不是再次清除和重新添加项目会容易得多。


推荐阅读