RelativeSource有四種類型
Self
FindAncestor
TemplatedParent
?文章來源地址http://www.zghlxwxcb.cn/news/detail-409606.html
a.Self
<Grid>
<Ellipse Width="{Binding RelativeSource={RelativeSource Self}, Path=Height}"
Height="100"
Fill="Black" />
</Grid>
?文章來源:http://www.zghlxwxcb.cn/news/detail-409606.html
b.FindAncestor
FindAncestor
顧名思義,當(dāng)綁定源是綁定目標(biāo)的祖先(父級)之一時(shí)使用此選項(xiàng)。使用FindAncestor擴(kuò)展,可以找到任何級別的祖先。
? ? ? ? ? ? ?
現(xiàn)在,讓我們使用FindAncestor擴(kuò)展將祖先的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">
<!-- 下面這個(gè)按鈕Content得到:Parent_2 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Name}" />
<!-- 下面這個(gè)按鈕Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=1}, Path=Name}" />
<!-- 下面這個(gè)按鈕Content得到:Parent_0 -->
<Button Height="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}" />
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</Grid>
?
c.TemplatedParent
<Window.Resources>
<ControlTemplate x:Key="template1">
<!--
在應(yīng)用模板時(shí),按鈕的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}" />
?
d.PreviousData
?
最終效果圖
?
?
?
到了這里,關(guān)于wpf RelativeSource綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!