WPF DataGrid绑定只能单向工作
本文关键字:单向工作 绑定 DataGrid WPF | 更新日期: 2023-09-27 17:57:55
我想绑定我的DataGrid列。首先我在DataGrid:中创建列
translationDataGrid = new DataGrid
{
IsReadOnly = true,
};
var fact = new FrameworkElementFactory(typeof(CheckBox));
fact.SetBinding(CheckBox.IsCheckedProperty, new Binding("Check") {Mode = BindingMode.TwoWay});
translationDataGrid.Columns.Add(new DataGridTemplateColumn
{
CellTemplate = new DataTemplate {VisualTree = fact}
});
translationDataGrid.Columns.Add(new DataGridTextColumn
{
Header = "Name",
Binding = new Binding("Name"),
Width = 250
});
然后我有一个类,我用它来创建要添加到DataGrid的对象:
private class ObjectToDataGrid : INotifyPropertyChanged
{
private bool _check;
public bool Check
{
get { return _check; }
set
{
_check = value;
NotifyPropertyChanged("Check");
}
}
public string Name { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
}
在这里,我将对象添加到DataGrid:
public void AddToDataGrid(string tag)
{
translationDataGrid.Items.Add(
new ObjectToDataGrid
{
Check = false,
Name = tag,
});
}
问题是,它只是单向变化。如果我更改数据,如下所示:
foreach (ObjectToDataGrid row in translationDataGrid.Items)
{
row.Check = check;
}
网格中的数据会按照预期发生变化。但当我选中checkBox,然后尝试从底层对象中检索Checked值时,它没有改变。
我已经找了几个小时的解决方案,但找不到。有人能帮忙吗?
尝试将UpdateSourceTrigger
设置为UpdateSourceTrigger.PropertyChanged
new Binding("Check") {
Mode = BindingMode.TwoWay ,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
}