WPF MVVM - 从祖先视图模型绑定到属性

ama*_*ha4 1 c# data-binding wpf relativesource mvvm

我有一组类似于以下内容的视图/视图模型:

CustomDialogView
  CustomView
    CustomListView
      CustomControl
        -SomeCustomProperty
Run Code Online (Sandbox Code Playgroud)

这些视图中的每一个都绑定到适当的视图模型。

我正在尝试将 SomeCustomProperty 绑定到 CustomDialogView 视图模型上的属性。

做这个的最好方式是什么?我尝试了一些事情,其中​​最有希望的似乎是通过 RelativeSource FindAncestor 设置此属性的绑定,例如:

<CustomControl
    SomeCustomProperty="{
        Binding RelativeSource={RelativeSource FindAncestor,
        AncestorType={x:Type sourcePath:CustomDialogViewModel}},
        Path=SomeCustomProperty,
        Mode=OneWay/>
</CustomControl>
Run Code Online (Sandbox Code Playgroud)

但我在这里根本没有任何约束力。

我不确定它是否有任何意义,但 CustomListView 是由工厂填充的。

Fru*_*erg 5

FindAncestor正在寻找一个视图而不是绑定的视图模型。因此,您需要将视图的类型设置为AncestorType. 现在,您可以通过添加访问此视图的视图模型DataContextPath结合。

<CustomControl
    SomeCustomProperty="{
        Binding RelativeSource={RelativeSource FindAncestor,
        AncestorType={x:Type sourcePath:CustomDialogView}},
        Path=DataContext.SomeCustomProperty,
        Mode=OneWay/>
</CustomControl>
Run Code Online (Sandbox Code Playgroud)