c# - 网格未更新
问题描述
我的 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));
}
}
}
解决方案
尝试将您的 XAML 代码更改为以下代码 -
<... ItemsSource="{Binding Path=MyCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ... />
实际上,我认为重新初始化 ObservableCollection 而不是再次清除和重新添加项目会容易得多。
推荐阅读
- loops - 如何在 Tcl 的一个参数中使用带有多个变量的 puts?
- php - PHP连接被拒绝
- swift - 通过匹配对 Realm 中的过滤结果进行排序
- javascript - React JS-发送POST请求时CORS缺少允许标头
- python - ProjError:x、y、z 和时间必须相同大小
- python - 错误 sqlite3.OperationalError:靠近“=”:语法错误
- c - CS50 可读性项目中的错误,只有 1 个输入,其他所有输入都有效
- malloc - GNU malloc 大小类
- discord.py - Discord python bot创建:清除消息命令,显示删除了多少消息
- meteor - Meteor 查询在服务器上运行得非常好,但在客户端上却不行