Search code examples
wpfdata-bindingdatagrid

How to programatically get the binding expression from a DataGridCheckBoxColumn


Given a datagrid with a DataGridCheckBoxColumn bound to a boolean object

<datagrid .....>
<DataGrid.Columns>
   <DataGridCheckBoxColumn  Header="Issues"  Binding="{Binding HasIssue,UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>

How can I programmatically obtain the Binding Expression to be able to call UpdateTarget() ?

ie.

   var expression = datagrid1.GetBindingExpression(DataGrid.**WhatProperty**);
    if (expression != null)
       expression .UpdateTarget();

I have also tried

var expression = BindingOperations.GetBindingExpression(datagrid1, ***`WhatDependencyObjectHere`***);

Solution

  • To answer your exact question, you would have to get the actual CheckBox that the DataGridCheckBoxColumn is generating. Here's an example function. I don't know what type of collection your ItemsSource is, so I called mine TestObject and set ItemsSource to an IList<TestObject>.

    static void UpdateBindingTarget(DataGrid dg, DataGridCheckBoxColumn col, TestObject item)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(item);
        CheckBox cb = (CheckBox)col.GetCellContent(row);
        var be = cb.GetBindingExpression(CheckBox.IsCheckedProperty);
        if (be != null) { be.UpdateTarget(); }
    }
    

    The real question is why you would want to do this in the first place. The above is not what I would consider good practice, more of a hacky workaround. If you need your binding source to update the target, it should either inherit DependencyObject and use a DependencyProperty, or implement INotifyPropertyChanged and raise the PropertyChanged event.