Self
FindAncestor
TemplatedParent
<Grid>
<Ellipse Width="{Binding RelativeSource={RelativeSource Self}, Path=Height}"
Height="100"
Fill="Black" />
</Grid>
FindAncestor
顧名思義,當繫結源是繫結目標的祖先(父級)之一時使用此選項。使用FindAncestor擴充套件,可以找到任何級別的祖先。
現在,讓我們使用FindAncestor擴充套件將祖先的Name屬性繫結到子元素button的Content屬性。
<Grid Name="Parent_3">
<StackPanel Name="Parent_222"
Width="100"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<StackPanel Name="Parent_2"
Width="100"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border Name="Parent_1">
<StackPanel x:Name="Parent_0"
Orientation="Vertical">
<!-- 下面這個按鈕Content得到:Parent_2 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Name}" />
<!-- 下面這個按鈕Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=1}, Path=Name}" />
<!-- 下面這個按鈕Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}" />
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Grid>
<Window.Resources>
<ControlTemplate x:Key="template1">
<!--
在應用模板時,按鈕的Background(Beige)與橢圓的Fill屬性相對繫結,Content(Click me)與ContentPresenter的Content屬性相對繫結。依賴值生效並給出以下輸出。
-->
<Canvas>
<Ellipse Width="155"
Height="110"
Fill="Black" />
<Ellipse Width="150"
Height="100"
Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
<ContentPresenter Margin="35"
Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />
</Canvas>
</ControlTemplate>
</Window.Resources>
<Button Height="0"
Margin="5"
Background="Beige"
Content="Click me"
FontSize="18"
Template="{StaticResource template1}" />
最終效果圖