我如何绑定到RelativeSource Self? [英] How do I bind to RelativeSource Self?

查看:19
本文介绍了我如何绑定到RelativeSource Self?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to bind several different properties in my Xaml:

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

您会注意到我在这里使用了两种不同的绑定技术.使用 Element Name 的那些有效,其他的则无效.这是后面的代码:

You will noticed I have used two Different binding techniques here. The ones using Element Name work, the other does not. Here is code behind:

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(""));

每个绑定都有不同的名称,但大多数情况下它们都是这样的.我希望我的绑定能够使用:

Each Binding has a different name but they all look like this for the most part. I want my Binding to be able to work with:

{Binding Description}

代替:

{Binding Path=Description, ElementName=_UserInputOutput}

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

It only seems to be working when ElementName is used. I need to export/import this XAML, so I can't have a ElementName or the import won't work.

我认为这是最好的:

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

这不起作用.

有什么想法吗??谢谢!

Any ideas?? Thank you!

推荐答案

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

You haven't set the DataContext, which is what the RelativeSource is using to determine what it's relative to. You need to set the DataContext at a higher level, like the UserControl. I typically have:

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

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

This tells the UserControl to bind itself the class in the codebehind.

这篇关于我如何绑定到RelativeSource Self?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆