[英]WPF DataGrid binding confusion
我对WPF数据绑定有些困惑。 我已经尝试了很多示例,但是我认为我不了解该主题的基础。
我有以下数据网格,绑定到ObservableCollection(Of T),其中T类具有Name属性,该属性显示在datagrid列中。 我的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的绑定方式如下:
<DataGrid ItemsSource="{Binding CollectionName}">
...
</DataGrid>
我猜想是针对使用该集合的,因此不需要以编程方式执行.ItemsSource ...但我无法使其运行。
有人可以给我看隧道尽头的光吗?
您可以对DataGrid的ItemsSource
进行数据绑定,而无需手动分配。 简单地声明MyCollection
公共财产,提高PropertyChanged
适当的通知,并设置DataContext
你DataGrid
(或设置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中的绑定:
<DataGrid Grid.Row="1" Name="MyDataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}" >
并且应该在不设置ItemsSource
但将其DataContext设置为集合的情况下工作:
public void InitApp() {
MyCollection = [... taking data from somewhere ...];
MyDataGrid.DataContext = MyCollection;
}
从理论上讲(因为我没有在这个问题中专门尝试过场景),使用ItemsSource
绑定时,当手动重新设置ItemsSource
不会带来相同的效果时,只要重新加载集合,您的DataGrid就会自动更新。
您没有解释最重要的部分,即如何实现填充? 如果通过将新集合引用分配给旧变量来执行此操作,则它将无法正常工作,因为该集合是一种引用类型,可以解决您的问题,您可以执行以下两项操作之一(在您的解决方案旁边):第一是定义将ObservableCollection作为窗口中的Dependency属性,然后可以使用它。 第二个也是最简单的方法是清除集合,然后使用源集合中的foreach循环添加新项目,这是第一种情况的示例:
public static readonly DependencyProperty MyCollectionProperty = DependencyProperty.Register("MyCollection", typeof(ObservableCollection<T>), typeof(MainWindow));
public ObservableCollection<T> MyCollection
{
get
{
return this.GetValue(MyCollectionProperty) as string;
}
set
{
this.SetValue(MyCollectionProperty, value);
}
}
//assign the collection value at any time
MyCollection = ......
//you can bind it as the past
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.