Search code examples
c#wpfxamlbindingrelativesource

Can't use RelativeSource in binding


I'm creating a modal dialog from a window and I need to bind a combo box in the dialog to a view model but not the one in its own DataContext. Instead, I need to bind the combo box to a property in the view model of the window that created the dialog.

The mark-up is as follows.

<ComboBox x:Name="Options"
          ItemsSource="{Binding 
            RelativeSource={
              RelativeSource FindAncestor,
              AncestorType=x:Type Window},
            Path=DataContext.AllOptions}"
          ...
          Style="{StaticResource DefaultComboBoxStyle}" />

I'm trying to follow the different suggestions from SO but I'm only landing in the following error. There's also a list of binding examples, which doesn't make me any more clever.

{"'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '131' and line position '15'."}

And the inner exception is as follows.

{"Character 'w' was unexpected in string 'x:Type Window'. Invalid XAML type name."}

I've tried with other thing then Window, including the name of the creating window (ProgramWindow) but it complained about the same character - "w"! And when I took awhile shot at x:Type Program (no w's!) it complained about the character "m", instead.

I'm not sure I understand why, so an explanation on that would be great. Of course, my question is what I'm missing. Should I add anything to the window tag of the dialog? Do I need to tell the computer that the ancestoring window's view model is going to be used as a relative source?


Solution

  • Try:

    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type x:Window}}
    

    You are missing the Mode= and the braces around the ancestor type. Braces are required for x:Type.