简体   繁体   中英

WPF DataGrid Binding only works one-way

I want to bind my DataGrid columns. First I create the columns in 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
});

Than I have a class which I use to create objects to add to 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));
    }
}

And here I add objects to DataGrid:

public void AddToDataGrid(string tag)
{
    translationDataGrid.Items.Add(
        new ObjectToDataGrid
        {
            Check = false,
            Name = tag,
        });
}

The problem is, that it only changes one-way. If I change the data, like this:

foreach (ObjectToDataGrid row in translationDataGrid.Items)
{
    row.Check = check;
}

data in grid change as they supposed to. But when I check the checkBox, and than try to retrieve Checked value from the underlying object, its unchanged.

I've been looking for a solution for several hours now, but I can't find it. Can someone please help?

try set UpdateSourceTrigger to UpdateSourceTrigger.PropertyChanged

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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