我如何使用WPF绑定的RelativeSource,有哪些不同的用例?
当前回答
值得注意的是,对于那些无意中发现Silverlight的想法的人:
Silverlight只提供了这些命令的一个简化子集
其他回答
值得注意的是,对于那些无意中发现Silverlight的想法的人:
Silverlight只提供了这些命令的一个简化子集
在WPF中,RelativeSource绑定公开了三个属性来设置:
1. Mode:这是一个枚举,可以有四个值:
a. PreviousData(value=0):它将属性的上一个值赋给 约束函数 b. TemplatedParent(value=1):在定义的模板时使用 任何控件,并希望绑定到控件的值/属性。 例如,定义ControlTemplate:
<ControlTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ControlTemplate>
c. Self(value=2):当我们想从一个Self或Self的属性绑定时。 例如:在设置复选框上的命令时,将复选框的选中状态发送为CommandParameter
<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />
d. FindAncestor(value=3):当想从父控件绑定时 在可视化树中。 例如:在记录中绑定一个复选框,如果选中了网格,如果选中了标题复选框
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />
2. 祖宗类型:当模式是find祖宗,然后定义什么类型的祖先
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}
3.祖宗级别:当模式是FindAncestor时,那么祖先的级别是什么(如果在可视树中有两个相同类型的父)
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}
以上是RelativeSource绑定的所有用例。
这里有一个参考链接。
我没有阅读每个答案,但我只是想添加这个信息,以防按钮的相对源命令绑定。
当你使用Mode= find祖宗的相对源时,绑定必须像这样:
Command="{Binding Path=DataContext.CommandProperty, RelativeSource={...}}"
如果你没有在你的路径中添加DataContext,在执行时它不能检索属性。
不要忘记TemplatedParent:
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
or
{Binding RelativeSource={RelativeSource TemplatedParent}}
这是我在空数据网格上使用该模式的一个示例。
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
推荐文章
- 如何从字符串中删除新的行字符?
- 是否已经添加了事件处理程序?
- Lookup()和Dictionary(Of list()的区别
- 如何从我的c#代码运行EXE文件?
- Node.js vs .Net性能
- .NET控制台应用程序中的全局异常处理程序
- 枚举上最常见的c#位操作
- PowerShell脚本在机器上返回。net框架的版本?
- WPF数据网格底部空行
- 用c#创建一个空文件
- 如何改变列表<T>数据IQueryable<T>数据
- 您可以使用反射来查找当前正在执行的方法的名称吗?
- 流。Seek(0, SeekOrigin.Begin)或Position = 0
- 如果查询为空,则最大返回值
- 传递一个实例化的系统。类型作为泛型类的类型参数