2017-10-08 419 views
0

我有類似於以下視圖/視圖模型巢: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由工廠填充。

回答

2

FindAncestor正在查找未綁定的ViewModel。由於這個事實,你需要設置視圖的類型爲AncestorType。現在,您可以通過將DataContext添加到Path來綁定,從而訪問此視圖的ViewModel。

<CustomControl 
    SomeCustomProperty="{ 
     Binding RelativeSource={RelativeSource FindAncestor, 
     AncestorType={x:Type sourcePath:CustomDialogView}}, 
     Path=DataContext.SomeCustomProperty, 
     Mode=OneWay/> 
</CustomControl> 
+0

非常好!謝謝 :) – amarsha4

相關問題