Search code examples
c#wpfmvvmdata-bindingrelativesource

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.


Solution

  • 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>