2
votes

I've written an Interactivity Behavior (from Blend SDK) , which can be attached to a DataGrid, and does some magic with the DataGrid's columns based on the ViewModel in the DataContext of the DataGrid.
Since the DataContext can be set later, I have to listen for DataContext changes in the behavior. So, I've bound a DependencyProperty to the Associated DataGrid's DataContext, like this:

 BindingOperations.SetBinding(this, SourceProperty, new Binding("DataContext") { Source = AssociatedObject });

This line is hit, so the binding does happen.

Now the tricky part: if I call

datagrid.DataContext = new MyViewModel();

everything works perfectly. But, if the datagrid is contained in some UserControl (not necessarily its immediate child) and I want to call

this.DataContext = new MyViewModel();

the callback of the Source property DOESN'T fire. I debugged it, the datagrid.DataContext is set, so the DataContext is inherited through the visual tree, as it should be, if I manually call update on the behavior, it does see the DataContext, but nothing happens automatically.
I don't want to name the DataGrid instance, I don't want to name the behavior, since there can be any number of those in one UserControl, I want to set the UserControl's DataContext and let the DependencyProperty system work its magic.

What am I doing wrong?

1
Try to set binding in an opposite way: SetBinding(AssociatedObject, FrameworkElement.DataContextProperty, new Binding("Source") { Source = this, Mode = BindingMode.TwoWay}); - vortexwolf
@vorrtex: That sounds like an answer not a comment. Perhaps its placed strategically because its wrong. - AnthonyWJones
@vorrtex: everything is the same, nothing changed. - TDaver

1 Answers

2
votes

Have you tried something simpler:-

  BindingOperations.SetBinding(this, SourceProperty, new Binding());

This should give you the DataContext object. A binding without a Path returns the source object. A binding without an explicit Source returns the current DataContext.

The question is does does the DataContext of this (the behaviour) aquire its value from the DataGrid to which its attached? I think it probably does.