【发布时间】:2013-03-07 19:54:41
【问题描述】:
我正在尝试从该控件的 ResourceDictionary 中引用我的 WPF 控件中的元素。这是一个例子:
<UserControl.Resources>
<ResourceDictionary>
<Behaviors:GridViewInteractionModel x:Key="gridViewInteraction" GridView="{Binding ElementName=myGridView}"/>
</ResourceDictionary>
</UserControl.Resources>
...
<SomeGridView x:Name="myGridView"/>
GridViewInteractionModel 对象上的GridView 依赖属性的值应该是名为myGridView 的SomeGridView 对象。
上面的代码不起作用。 {Binding ElementName=myGridView} 没有绑定元素(GridViewInteractionModel 的 SetValue 函数永远不会被调用)。
WPF 运行时错误是:
Cannot find source for binding with reference 'ElementName=myGridView'.
BindingExpression:(no path); DataItem=null; target element is
'GridViewInteractionModel' (HashCode=15238415); target property is
'GridView' (type 'SomeGridView')
有谁知道如何让控件中的元素绑定到 ResourceDictionary 中资源的属性?
我发现获取属性集的唯一方法是在调用 InitializeComponent() 之后像这样在代码隐藏构造函数中手动设置它:
(Resources["gridViewInteraction"] as GridViewInteractionModel).GridView = FindName("myGridView") as SomeGridView;
但这真的很难看(而且容易出错)。
谢谢。
【问题讨论】:
标签: wpf binding resourcedictionary