ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WPF教程(四)RelativeSource属性

2020-12-13 13:01:07  阅读:220  来源: 互联网

标签:控件 教程 http xaml 偏移量 RelativeSource AncestorType WPF


我们进行Bingding时,如果明确知道数据源的Name,就能用Source或者ElementName进行绑定,但是有时候我们需要绑定的数据源可能没有明确的Name,此时我们就需要利用Bingding的RelativeSource进行绑定,这种办法的意思是指当前元素和绑定源的位置关系。

(1)控件关联自身的属性——Self

 

<Window x:Class="RelativeSource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBox Height="30" Width="60" Name="Box1" Text="{Binding RelativeSource={RelativeSource Mode=self},Path=Name }"/>
</StackPanel>
</Grid>
</Window>

 

上例是前台xaml写法,再看下后台怎么实现:

public MainWindow()
{
InitializeComponent();
System.Windows.Data.RelativeSource rs = new System.Windows.Data.RelativeSource();
rs.Mode = RelativeSourceMode.Self;
Binding binding = new Binding("Name") { RelativeSource = rs };
this.Box1.SetBinding(TextBox.TextProperty, binding);
}

 

(2)控件关联其父级容器的属性——AncestorType

<Window x:Class="RelativeSource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Name="G1">
<Grid Name="G2">
<StackPanel Name="S1">
<TextBox Height="30" Width="60" Name="Box1" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=2},Path=Name }"/>
</StackPanel>
</Grid>
</Grid>
</Window>

 

详细介绍下AncestorLevel,它指的是以Bingding目标控件为起点的层级偏移量,S1的偏移量是1,G2的偏移量是2,G1是偏移量3,AncestorType指的是要找的目标对象的类型。值得注意的是AncestorLevel必须参考AncestorType使用,如上面设置了AncestorType={x:Type Grid},则Bingding在寻找时会忽略非Grid的控件,此时G2的偏移量是1,G1的偏移量是2,StackPanel被忽略。

(3)控件关联模板的属性——TemplatedParent

 

<Window.Resources>
<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>
</Window.Resources>

总结

从运用性上介绍了RelativeSource三种使用方法,目前就碰到三种,有新的会继续更。知识是没有边界的,不断地探知即为知识来源,取之不竭、用之不尽。刚刚新开项目,安排了不少任务,有时间再写。

 

标签:控件,教程,http,xaml,偏移量,RelativeSource,AncestorType,WPF
来源: https://www.cnblogs.com/bruce1992/p/14128375.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有