Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid: How to get binding expression of a cell?

I need to get access to the binding expression of the DataGrid cell in a DataGridTextColumn. For example:

        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

I managed to get the TextBlock associated with the cell:

        var cell = dataGrid.GetCellCtrl<TextBlock>(dataGrid.CurrentCell);

And cell seems to be correct. I can call

        cell.SetValue(TextBlock.TextProperty, value);

To update the cell text. It seems to be working on the grid (number updated). However, as I realize after a while, the source doesn't get updated. It didn't help even if I turn UpdateSourceTrigger to PropertyChange. Then, I thought I need to get the binding expression and call UpdateSource explicitly.

        var bindingExpr = cell.GetBindingExpression(TextBlock.TextProperty);

but bindingExpr is always null. Why?

EDIT: The original problem I had was that I can get to the binding TextBlock for the cell, and set the TextBlock.TextProperty. However, the source doesn't get updated. This is something I'm trying to resolve this problem.

like image 726
newman Avatar asked Mar 05 '13 05:03

newman


1 Answers

The TextBox in the DataGridTextColumn will not have a binding expression the column itself has the binding.

DataGridTextColumn is derived from DataGridBoundColumn which uses a BindingBase property not TextBlock.TextProperty, However the Binding property is not a DependancyProperty so you will have to access using normal public properties.

So you will have to do a bit of casting as the Binding property in DataGridTextColumn is type BindingBase.

Something like this should work (untested)

var binding = (yourGrid.Columns[0] as DataGridBoundColumn).Binding as Binding;
like image 136
sa_ddam213 Avatar answered Sep 28 '22 04:09

sa_ddam213