简体   繁体   中英

WPF MVVM - Bind to a property from an ancestor view model

I have a nest of views/view models similar to the following:

CustomDialogView
  CustomView
    CustomListView
      CustomControl
        -SomeCustomProperty

Each of these views is bound to an appropriate view model.

I'm trying to bind SomeCustomProperty to a property on CustomDialogView's view model.

What is the best way to do this? I have tried a few things, the most promising of which seemed to be setting the binding of this property through RelativeSource FindAncestor like:

<CustomControl
    SomeCustomProperty="{
        Binding RelativeSource={RelativeSource FindAncestor,
        AncestorType={x:Type sourcePath:CustomDialogViewModel}},
        Path=SomeCustomProperty,
        Mode=OneWay/>
</CustomControl>

But I'm getting no binding here at all.

I'm not sure if it has any bearing but the CustomListView is populated by a factory.

FindAncestor is finding a View not the bound ViewModel. Due to that fact you need to set the type of the View as AncestorType . Now you are able to access the ViewModel of this View by adding DataContext to the Path to bind.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM