WPF MVVM - 绑定到一个属性从一个祖先视图模型
问题描述:
我有类似于以下视图/视图模型巢:WPF MVVM - 绑定到一个属性从一个祖先视图模型
CustomDialogView
CustomView
CustomListView
CustomControl
-SomeCustomProperty
这些视图每个绑定到适当的视图模型。
我想将SomeCustomProperty绑定到CustomDialogView的视图模型上的一个属性。
这样做的最好方法是什么?我已经尝试了一些东西,其中最有希望的似乎要通过的RelativeSource FindAncestor像设置该属性的结合:
<CustomControl
SomeCustomProperty="{
Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type sourcePath:CustomDialogViewModel}},
Path=SomeCustomProperty,
Mode=OneWay/>
</CustomControl>
但我发现了在这里没有约束力的。
我不确定它是否有任何方位,但CustomListView由工厂填充。
答
FindAncestor
正在查找未绑定的ViewModel。由于这个事实,你需要设置视图的类型为AncestorType
。现在,您可以通过将DataContext
添加到Path
来绑定,从而访问此视图的ViewModel。
<CustomControl
SomeCustomProperty="{
Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type sourcePath:CustomDialogView}},
Path=DataContext.SomeCustomProperty,
Mode=OneWay/>
</CustomControl>
非常好!谢谢 :) – amarsha4