网格未更新

时间:2018-07-21 10:02:44

标签: c# wpf observablecollection

我在C#/ WPF应用程序中具有以下代码。单击“刷新”按钮后,我在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));


        }


    }



}

1 个答案:

答案 0 :(得分:0)

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

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

实际上,我认为重新初始化ObservableCollection比重新清除并重新添加项目要容易得多。