【问题标题】:Silverlight Behavior: DataContext of AssociatedObject changesSilverlight 行为:AssociatedObject 更改的 DataContext
【发布时间】:2011-06-21 08:00:59
【问题描述】:

我已经编写了一个交互行为(来自 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 系统发挥其魔力。

我做错了什么?

【问题讨论】:

  • 尝试以相反的方式设置绑定:SetBinding(AssociatedObject, FrameworkElement.DataContextProperty, new Binding("Source") { Source = this, Mode = BindingMode.TwoWay});
  • @vorrtex:这听起来像是答案而不是评论。也许它的战略位置是因为它的错误。
  • @vorrtex:一切都一样,没有任何改变。

标签: silverlight silverlight-4.0 datacontext dependency-properties behavior


【解决方案1】:

你有没有尝试过更简单的方法:-

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

这应该为您提供 DataContext 对象。没有Path 的绑定返回源对象。没有显式 Source 的绑定会返回当前的 DataContext

问题是this(行为)的DataContext 是否从其所附加的DataGrid 中获取其值?我想它可能会。

【讨论】:

  • 哇,真是个惊喜。 Behavior只是一个DependencyObject,DataContext在FrameworkElement上,却奇迹般地起作用了。
猜你喜欢
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多