WPF DataGrid绑定仅适用于单向

时间:2016-07-21 08:36:51

标签: c# wpf data-binding

我想绑定我的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值时,它保持不变。

我一直在寻找几个小时的解决方案,但我找不到它。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

尝试将UpdateSourceTrigger设置为UpdateSourceTrigger.PropertyChanged

new Binding("Check") { 
                       Mode = BindingMode.TwoWay , 
                       UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged 
                     }