我如何使用WPF绑定的RelativeSource,有哪些不同的用例?
当前回答
我没有阅读每个答案,但我只是想添加这个信息,以防按钮的相对源命令绑定。
当你使用Mode= find祖宗的相对源时,绑定必须像这样:
Command="{Binding Path=DataContext.CommandProperty, RelativeSource={...}}"
如果你没有在你的路径中添加DataContext,在执行时它不能检索属性。
其他回答
我创建了一个库来简化WPF的绑定语法,包括让它更容易使用RelativeSource。这里有一些例子。之前:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}
后:
{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}
下面是一个如何简化方法绑定的示例。之前:
// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
get {
if (_saveCommand == null) {
_saveCommand = new RelayCommand(x => this.SaveObject());
}
return _saveCommand;
}
}
private void SaveObject() {
// do something
}
// XAML
{Binding Path=SaveCommand}
后:
// C# code
private void SaveObject() {
// do something
}
// XAML
{BindTo SaveObject()}
你可以在这里找到图书馆:http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html
请注意,在我用于方法绑定的“BEFORE”示例中,代码已经通过使用RelayCommand进行了优化,我最后检查它不是WPF的本机部分。没有这个BEFORE的例子会更长。
不要忘记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>
如果你想绑定到对象上的另一个属性:
{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
如果你想获取一个祖先的属性:
{Binding Path=PathToProperty,
RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
如果你想在父模板上获得一个属性(所以你可以在一个ControlTemplate中做2种方式绑定)
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
或者更短(这只适用于OneWay绑定):
{TemplateBinding Path=PathToProperty}
下面是MVVM架构的一个更直观的解释:
推荐文章
- c# .NET中的App.config是什么?如何使用它?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- Visual Studio弹出提示:“操作无法完成”
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间
- 由Jon Skeet撰写的《Singleton》澄清
- 自定义数字格式字符串始终显示符号
- Post参数始终为空
- string.ToLower()和string.ToLowerInvariant()
- 检查instance是否属于某个类型
- 将列表转换为逗号分隔的字符串
- Microsoft.Jet.OLEDB.4.0'提供程序未在本地机器上注册