[英]WPF DataGrid not updating - is it one-way binding?
C#,WPF。 我正在使用带有绑定的Datagrid
。 我的理解是,在实现INotifyPropertyChanged
,如果对象属性发生更改,则它们应在Datagrid
更新。
目前这并没有发生,尽管 II 已经实现了INotifyPropertyChanged
并且我从测试中知道PropertyChanged
事件正在触发。 我的猜测是绑定不是双向的(?)如果是这种情况,我不确定如何将其设置为双向。 绑定在XAML
设置, ItemsSource
稍后在代码隐藏中设置:
<DataGrid Name="dataGridxyz" ItemsSource="{Binding}">
dataGridxyz.ItemsSource = foo;
使用此语法在XAML
添加双向绑定会导致错误:
<DataGrid Name="dataGridxyz" ItemsSource="{Binding, Mode=TwoWay}">
所以我一直在寻找这样的东西:
dataGridxyz.ItemsSource = foo;
dataGridxyz.Binding.Mode = TwoWay;
可能我可以在XAML
或代码隐藏中将其设置为双向绑定......但我看不出如何做。
编辑:
以下是显示问题的最小功能示例。 它是真实事物的简化版本,是更大项目的一部分。
单击按钮时, Name
属性会更改,但不会在PropertyGrid
更新。
<Window x:Class="testBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow">
<Grid>
<StackPanel Orientation="Vertical">
<DataGrid Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True"/>
<Button Name="btn" Width="100" Height="20" Content="Test" Click="btn_Click"/>
</StackPanel>
</Grid>
namespace testBinding
{
public partial class MainWindow : Window
{
BindingList<foo> bar = new BindingList<foo>() { new foo() };
public MainWindow()
{
InitializeComponent();
dg.ItemsSource = bar;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
bar[0].Name = "Paul";
}
}
class foo : genericClass, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
class genericClass : INotifyPropertyChanged
{
private string _name = "John";
public string EyeColor = "Blue";
public bool Child = false;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Name
{
get { return _name; }
set
{
_name = value;
MessageBox.Show("Name changed!"); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
OnPropertyChanged("Name");
}
}
}
}
我通过猜测和反复试验找出了这里发生的事情。 感谢评论的人。
它不是由我最初推测的单向绑定引起的。
这个问题是由上例中的foo
对象继承自另一个类 ( genericClass
) 并且都实现INotifyPropertyChanged
。 很明显, foo
类中PropertyChanged
事件的存在阻止了DataGrid
更新。 我没有预料到这种行为,因为我知道继承类中的PropertyChanged
事件确实会触发并更新Name
属性。
如果我从foo
删除PropertyChanged
事件,则名称会按预期在 PropertyGrid 中更新。
class foo : genericClass, INotifyPropertyChanged
{
//public event PropertyChangedEventHandler PropertyChanged;
}
它给我留下了一个问题,即如何在一个以上的继承级别(即在一个类中和在它继承的一个类中处理属性更改,这似乎是一件有效的事情)……但这可能是一个不同的问题.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.