wpf RelativeSource绑定
WPF 绑定
2023-09-14 08:58:29 时间
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}" />
最终效果图
相关文章
- WPF 虚拟化 VirtualizingWrapPanel 和 VirtualLizingTilePanel
- VS2017 处理 Rdlc , microsoft report viewer 轻量级报表处理(WPF CS客户端版本)
- AYUI7 WPF MVC插件欣赏
- WPF一步一脚印系列(1):万事起头难
- wpf 菜单
- wpf 附加属性
- wpf DataGrid 分组
- wpf Binding ListBox
- (转)WPF控件开源资源
- .NET Core 3 WPF MVVM框架 Prism系列之导航系统
- WPF中的动画——(二)From/To/By 动画
- wpf toggleSwitch 的只读属性
- wpf中UserControl的几种绑定方式
- MindFusion.WPF Pack 2022.R2 Crack
- WPF MVVM从入门到精通6:RadioButton等一对多控件的绑定
- WPF DataGrid控件的使用 使用列模板来进行数据格式的美化