在WPF中如何使用RelativeSource綁定
阿新 • • 發佈:2017-08-25
背景 三種 pre light 相同 set bold csharp value
在WPF綁定的時候,指定綁定源時,有一種辦法是使用RelativeSource。
這種辦法的意思是指當前元素和綁定源的位置關系。
第一種關系: Self
舉一個最簡單的例子:在一個StackPanel中,有一個TextBlock。
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>
如果想讓textbox的width和height相同,通過設置屬性Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" 就可以實現。
第二種關系:TemplatedParent
例如為一個Button寫一個樣式,修改Button為橢圓型。同時需要橢圓的背景色和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>
在這個例子中 TemplateParent就是指的Button
第三種關系:AncestorType
指定綁定源為某個父元素
<Grid> <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/> </Grid>
這個例子中Label的背景色和Grid的背景色一樣。
在WPF中如何使用RelativeSource綁定