我如何绑定到的RelativeSource自我? [英] How do I bind to 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" />
您会注意到我在这里用了两个不同的结合技术。使用元素名称的工作的人,其他没有。这里是code背后:
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}}
这并不工作。
任何想法?谢谢!
推荐答案
您还没有设置DataContext的,这是什么的RelativeSource使用,以确定它的相对。您需要设置在DataContext在较高的水平,如用户控件。我通常有:
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>
这告诉用户控件本身的类绑定在codebehind。
This tells the UserControl to bind itself the class in the codebehind.
这篇关于我如何绑定到的RelativeSource自我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!