How to Use RelativeSource binding in WPF, wpfrelativesource
When binding WPF, when specifying the binding source, there is a way to use RelativeSource.
This method refers to the location relationship between the current element and the bound source.
First relationship: Self
For example, a StackPanel contains a TextBlock.
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>
To make the width and height of textbox the same, you can set the property Height = "{Binding RelativeSource = {RelativeSource Self}, Path = Width.
Second link:TemplatedParent
For example, write a style for a Button and change the Button to an elliptical type. At the same time, the background color of the ellipse must be the same as that of the Button.
<Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="Green"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <Ellipse> <Ellipse.Fill> <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/> </Ellipse.Fill> </Ellipse> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
In this example, TemplateParent refers to the Button
Third link:AncestorType
Specify the binding source as a parent Element
<Grid> <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/> </Grid>
In this example, the Label background color is the same as the Grid background color.