如何绑定到RelativeSource Self?

B-R*_*Rad 18 wpf binding

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

<Label Content="{Binding Description}" 
Visibility="{Binding Path=DescriptionVisibility, 
ElementName=_UserInputOutput}"               
FontSize="{Binding Path=FontSizeValue, ElementName=_UserInputOutput}"  
HorizontalAlignment="Left" VerticalAlignment="Top" Padding="0" />
Run Code Online (Sandbox Code Playgroud)

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

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(""));
Run Code Online (Sandbox Code Playgroud)

每个Binding都有不同的名称,但大多数都看起来像这样.我希望我的Binding能够使用:

{Binding Description}
Run Code Online (Sandbox Code Playgroud)

代替:

{Binding Path=Description, ElementName=_UserInputOutput}
Run Code Online (Sandbox Code Playgroud)

它只在使用ElementName时才起作用.我需要导出/导入这个XAML,所以我不能拥有ElementName,否则导入将无效.

我认为这是最好的:

{Binding Path=Description, RelativeSource={RelativeSource Self}}
Run Code Online (Sandbox Code Playgroud)

这没用.

有任何想法吗??谢谢!

H.B*_*.B. 35

{RelativeSource Self}目标拥有被绑定属性的对象,如果你有一个Label它将寻找的绑定,那就Label.Description不存在了.相反,你应该使用{RelativeSource AncestorType=UserControl}.

无源(绑定ElementName,Source,RelativeSource)是相对于DataContext,然而UserControls,你应该避免设置DataContext与外部绑定不乱.


Joe*_*csy 31

您尚未设置DataContext,这是RelativeSource用于确定它相对于什么的内容.您需要将DataContext设置为更高级别,例如UserControl.我通常有:

<UserControl ... DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>
Run Code Online (Sandbox Code Playgroud)

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

  • "这就是RelativeSource用来确定它相对于什么的东西"这句​​话显然是不正确的.设置UserControl的DataContext也不是一个好主意...... (13认同)
  • 我认为这不是一个好主意,因为它违反了MVVM范例:当我们想要将MVF与MVVM一起使用时,我们有一个绑定到其ViewModel的View.所以在View后面的代码的构造函数中我们说`View(){InitializeComponent(); DataContext = new ViewModel(); 这使得所有数据绑定操作都可以在ViewModel上运行,因此我们可以将视图与ViewModel分开. (4认同)