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();
eve开发者_开发知识库rything 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?
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.
精彩评论