[英]DataGrid itemsource binding not updating and binding in WPF not working
当 itemsource 以编程方式更改时,我无法成功更新我的 WPF Datagrid。
XAML
<DataGrid Name="ReaderGrid" ItemsSource="{Binding myData}" Height="Auto" Width="Auto" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeColumns="False" CanUserResizeRows="False" CanUserReorderColumns="False" IsReadOnly="True" GridLinesVisibility="None">
<DataGrid.Columns>
<DataGridTextColumn Header="Count" Width="*" FontSize="14" Binding="{Binding count}" />
<DataGridTextColumn Header="Total" Width="*" FontSize="14" Binding="{Binding total}" />
</DataGrid.Columns>
</DataGrid>
XAML.CS(代码隐藏)
public partial class MainWindow : Window
{
public ObservableCollection<obj> myData { get; set; }
public MainWindow()
{
InitializeComponent();
myData = new ObservableCollection<obj>();
InitializeMyData();
最后一个函数 (InitializeMyData()) 只是用测试信息填充 myData。
最后对象只是一些测试类
public class obj
{
public int count { get; set; }
public double total { get; set; }
}
代码 AS-IS 不起作用,除了我在 WPF 中的数据网格为空之外没有任何错误 - 我发现解决此问题的唯一方法是在初始化数据后添加以下代码
ReaderGrid.ItemsSource = myData;
现在显示了我所有的初始数据,除了在此之后的任何时间点,如果我更改 myData 我希望/期望更改自动反映在我的 WPF Datagrid 中,遗憾的是没有任何更新......
问题 - 为什么我的 WPF 绑定不起作用(为什么我需要在 ItemSource 后面的代码中显式设置),以及为什么对 myData 的更改没有更新我的 Datagrid?
谢谢,
像这样的绑定
ItemsSource="{Binding myData}"
没有明确定义绑定的源对象,而只定义源属性。 它要求设置绑定目标的 DataContext,然后将其用作源对象。
DataContext 从父元素继承到子元素,并且通常在窗口的构造函数中设置,如下所示。
这里是 MainWindow 实例,因为类 MainWindow 拥有源属性,但通常它是声明绑定源属性的视图模型类的实例(并且还实现 INotifyPropertyChanged 接口以通知属性值更改)。
public ObservableCollection<obj> myData { get; } = new ObservableCollection<obj>();
public MainWindow()
{
InitializeComponent();
InitializeMyData();
DataContext = this;
}
另请注意,根据广泛接受的编码约定,C# 属性名称以大写字母开头,因此您的属性最好命名为MyData
。
对于您的第二个问题,即未更新的数据,您的数据项类必须实现INotifyPropertyChanged
接口,例如:
public class obj : INotifyPropertyChanged
{
public event PropertyChanged;
private int _count;
public int Count
{
get { return _count; }
set
{
_count = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count"));
}
}
}
有关 WPF 数据绑定的所有详细信息,请参阅 MSDN 上的数据绑定概述文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.