我试图在我的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将自己绑定到代码隐藏中的类.
| 归档时间: |
|
| 查看次数: |
52098 次 |
| 最近记录: |