我对 WPF 数据绑定(bind)有点困惑。我尝试了很多示例,但我认为我不了解该主题的基础知识。
我有以下数据网格,绑定(bind)到一个 ObservableCollection(Of T),其中 T 类有一个名称属性,显示在数据网格列中。我的 T 类还实现了 INotifyPropertyChanged 并在 Name 属性更改时正确触发事件。
<DataGrid Grid.Row="1" Name="MyDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn x:Name="NameColumn" Header="Name" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
然后,在代码隐藏类中,我有提供数据网格的基础集合。
public ObservableCollection<T> MyCollection
{
get;
set;
}
最后,当我的应用程序启动时,我加载“MyCollection”属性并告诉数据网格使用该集合。
public void InitApp()
{
MyCollection = [... taking data from somewhere ...];
MyDataGrid.ItemsSource = MyCollection;
}
一切正常(数据显示正确)。但是,如果我重新加载集合(再次从某个地方获取完全不同的数据),如果我不再次执行 MyDataGrid.ItemsSource = MyCollection;指令,数据网格不会更新。
我认为每次重新加载数据时都使用 XXX.ItemsSource = YYY 不是一个好习惯,所以我想我做错了什么。在某些示例中,我看到 XAML DataGrid 的绑定(bind)方式如下:
<DataGrid ItemsSource="{Binding CollectionName}">
...
</DataGrid>
我猜是为了使用该集合,因此无需以编程方式执行 .ItemsSource...但我无法使其运行。
谁能告诉我隧道尽头的光?
最佳答案
您可以数据绑定(bind) DataGrid 的 ItemsSource
而不是手动分配它。只需将 MyCollection
声明为公共(public)属性,正确地引发 PropertyChanged
通知,并为您的 DataGrid
设置 DataContext
(或设置 DataContext
用于 DataGrid 所在的窗口):
private ObservableCollection<MyClass> _myCollection
public ObservableCollection<MyClass> MyCollection
{
get { return _myCollection; }
set
{
_myCollection = value;
NotifyPropertyChanged("MyCollection");
}
}
public void InitApp() {
MyCollection = [... taking data from somewhere ...];
MyDataGrid.DataContext = this;
}
<DataGrid ItemsSource="{Binding MyCollection}">
...
</DataGrid>
更新:
您的方法还在 XAML 中声明绑定(bind):
<DataGrid Grid.Row="1" Name="MyDataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}" >
这应该可以在不设置 ItemsSource
但将其 DataContext 设置为集合的情况下工作:
public void InitApp() {
MyCollection = [... taking data from somewhere ...];
MyDataGrid.DataContext = MyCollection;
}
理论上(因为我没有具体尝试过这个问题中的场景),使用 ItemsSource
绑定(bind)你的 DataGrid 将在集合重新加载时自动更新,当手动设置 ItemsSource
时可以'带来同样的效果。
关于c# - WPF DataGrid 绑定(bind)困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22064749/