There is a window that contains the following XAML markup:
<Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <ContentControl Grid.Row="0"> <ContentControl.Style> <Style TargetType="ContentControl"> <Style.Triggers> <DataTrigger Binding="{Binding Value}" Value="1"> <Setter Property="Content"> <Setter.Value> <Button Background="Aquamarine" Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestData}" /> </Setter.Value> </Setter> </DataTrigger> <DataTrigger Binding="{Binding Value}" Value="2"> <Setter Property="Content" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestData}" /> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style> </ContentControl> <Button Grid.Row="1" Command="{Binding DoCommand}" Content="Тыц" /> </Grid> In this window, the ContentControl element contains two DataTrigger , which, depending on the value of the Value property, set a different value to the Content property of the ContentControl element. In the first case, the Button element is set as the value, and the простой текст in the second, which is taken from the TestData property.
As you can see in the Button element there is a binding to the TestData property located in the ViewModel , and it is set as follows:
<Button Background="Aquamarine" Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestData}" /> those. When configuring the Binding , the RelativeSource property is used, which allows you to specify the binding source relative to the current object. The problem is that for some reason, the current Binding configuration for the button does not work, that is, the binding to the TestData property TestData not occur.
At the same time, a similar binding, in which a simple text is specified, works successfully.
<Setter Property="Content" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TestData}" /> In addition, if you rewrite the Binding for a button otherwise:
<Button Background="Aquamarine" Content="{Binding TestData}" /> then everything will work fine.
I would like to understand the features of this behavior, why is the binding in the button specified using RelativeSource not working, but the simple Binding opposite?
RelativeSourcenot working, what happens inside the magic? It would seem that the button in the visual tree is present so what is the problem then to take and find its parentWindowand bind to the property from itsDataContext. - sp7Content="{Binding TestData}"bindingContent="{Binding TestData}"in the button works, I expected similar behavior when usingRelativeSource. In fact, after all, these bindings set the same thing in just different ways or am I mistaken? - sp7