RelativeSource有四種類型 Self FindAncestor TemplatedParent PreviousData a.Self Self用於綁定源和綁定目標相同的場景中。對象的一個屬性與同一對象的另一個屬性綁定。 例如,讓我們取一個高度和寬度相同的橢圓。在XAML文件中添加下麵給 ...
Self
FindAncestor
TemplatedParent
<Grid>
<Ellipse Width="{Binding RelativeSource={RelativeSource Self}, Path=Height}"
Height="100"
Fill="Black" />
</Grid>
b.FindAncestor
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}" />
最終效果圖
我的系列文章
A.Sql Server2005 Transact-SQL 新兵器學習 B.MCAD學習
C.代碼閱讀總結
D.ASP.NET狀態管理
E.DB(資料庫)
F.WAP
G.WinForm
H.Flex
希望上面提到的知識對您有所提示,同時歡迎交流和指正
作者:aierong
出處:http://www.cnblogs.com/aierong
貼子以"現狀"提供且沒有任何擔保,同時也沒有授予任何權利!
本文版權歸作者所有,歡迎轉載!
原創技術文章和心得,轉載註明出處!這也是對原創者的尊重!