【问题标题】:How do I bind to RelativeSource Self?如何绑定到 RelativeSource Self?
【发布时间】:2012-08-13 06:48:50
【问题描述】:

我正在尝试在我的 Xaml 中绑定几个不同的属性:

<Label Content="{Binding Description}" 
Visibility="{Binding Path=DescriptionVisibility, 
ElementName=_UserInputOutput}"               
FontSize="{Binding Path=FontSizeValue, ElementName=_UserInputOutput}"  
HorizontalAlignment="Left" VerticalAlignment="Top" Padding="0" />

你会注意到我在这里使用了两种不同的绑定技术。使用元素名称的工作,另一个不工作。这是后面的代码:

public string Description
{
     get { return (string)GetValue(DescriptionProperty); }
     set { SetValue(DescriptionProperty, value); }
}
public static readonly DependencyProperty DescriptionProperty = 
DependencyProperty.Register("Description", typeof(string), typeof(UserControl), 
new UIPropertyMetadata(""));

每个绑定都有不同的名称,但它们大部分看起来都像这样。 我希望我的 Binding 能够使用:

{Binding Description}

代替:

{Binding Path=Description, ElementName=_UserInputOutput}

似乎只有在使用 ElementName 时才有效。我需要导出/导入此 XAML,所以我不能有 ElementName,否则导入将不起作用。

我认为这是最好的:

{Binding Path=Description, RelativeSource={RelativeSource Self}}

这不起作用。

有什么想法吗??谢谢!

【问题讨论】:

标签: wpf binding


【解决方案1】:

您还没有设置 DataContext,RelativeSource 使用它来确定它的相对对象。您需要在更高级别设置 DataContext,例如 UserControl。我通常有:

<UserControl ... DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>

这告诉 UserControl 将自己绑定到代码隐藏中的类。

【讨论】:

  • "这是RelativeSource 用来确定它的相对对象" 该陈述完全不正确。设置 UserControl 的 DataContext 也不是一个好主意...
  • 我认为这不是一个好主意,因为它违反了 MVVM 范例:当我们想将 WPF 与 MVVM 一起使用时,我们有一个绑定到其 ViewModel 的 View。所以在 View 后面代码的构造函数中,我们说 View() { InitializeComponent(); DataContext = new ViewModel(); } 这使得所有数据绑定操作都在 ViewModel 上进行,因此我们可以将 View 与 ViewModel 分开。
  • 您不太可能想要(甚至不需要)执行此处建议的操作。赞成票似乎不明智。
【解决方案2】:

{RelativeSource Self} 以拥有被绑定属性的对象为目标,如果您在Label 上有这样的绑定,它将寻找不存在的Label.Description。相反,您应该使用{RelativeSource AncestorType=UserControl}

没有源的绑定(ElementNameSourceRelativeSource)相对于DataContext,但是在UserControls 中,您应该avoid setting the DataContext 以免与外部绑定混淆。

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多