You can bind to a property of an ancestor in the visual tree by using a RelativeSource
binding. The nearest control higher in the visual tree which has the same type or is derived from the type you specify will be used as the binding's source:
<Grid Background="Blue">
<Grid Background="Gray" Margin="10">
<Border Background="Red" Margin="20">
<StackPanel Background="White" Margin="20">
<Button Margin="10" Content="Button1" Background="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}}}" />
<Button Margin="10" Content="Button2" Background="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}" />
</StackPanel>
</Border>
</Grid>
</Grid>
In this example, Button1 has a gray background because the closest Grid
ancestor has a gray background. Button2 has a white background because the closest ancestor derived from FrameworkElement
is the white StackPanel
.