Silverlight 行为:AssociatedObject 的 DataContext 更改
我编写了一个交互行为(来自 Blend SDK),它可以附加到 DataGrid,并根据 DataGrid 的 DataContext 中的 ViewModel 对 DataGrid 的列执行一些操作。
由于可以稍后设置 DataContext,因此我必须监听 DataContext 行为的变化。因此,我将 DependencyProperty 绑定到关联的 DataGrid 的 DataContext,如下所示:
BindingOperations.SetBinding(this, SourceProperty, new Binding("DataContext") { Source = AssociatedObject });
点击此行,因此绑定确实发生。
现在是棘手的部分: 如果我称
datagrid.DataContext = new MyViewModel();
一切正常。但是,如果数据网格包含在某些 UserControl(不一定是其直接子控件)中,并且我想调用
this.DataContext = new MyViewModel();
Source 属性的回调,则不会触发。我调试了它,设置了 datagrid.DataContext,因此 DataContext 是通过可视化树继承的,因为它应该是这样,如果我手动调用行为更新,它确实会看到 DataContext,但不会自动发生任何事情。
我不想命名 DataGrid 实例,我不想命名行为,因为一个 UserControl 中可以有任意数量的行为,我想设置 UserControl 的 DataContext 并让 DependencyProperty 系统发挥其魔力。
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过更简单的方法:-
这应该为您提供 DataContext 对象。没有
Path
的绑定返回源对象。没有显式Source
的绑定返回当前的DataContext
。问题是
this
(行为)的DataContext
是否从其附加的DataGrid
获取其值?我想可能是这样。Have you tried something simpler:-
This should give you the DataContext object. A binding without a
Path
returns the source object. A binding without an explicitSource
returns the currentDataContext
.The question is does does the
DataContext
ofthis
(the behaviour) aquire its value from theDataGrid
to which its attached? I think it probably does.