繁体   English   中英

WPF DataGrid绑定只能单向运行

[英]WPF DataGrid Binding only works one-way

我想绑定我的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 
                     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM