我正在创建一个UserControl
我想用这样的东西:
<controls:ColorWithText Color="Red" Text="Red color" />
到目前为止,我已经实现了类似的控件,如下所示:
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" >
<Border Width="15" Height="15" Background="{Binding Color, ElementName=ThisControl}" />
<TextBlock Text="{Binding Text, ElementName=ThisControl}" />
</StackPanel>
</UserControl>
where Color
and Text
是代码中定义的控件的依赖属性。这可行,但指定ElementName
每次都显得没有必要。
另一个有效的选择是使用
<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">
并且没有指定ElementName
s,但这对我来说似乎也不是一个干净的解决方案。
我有两个问题:
- 为什么不
<UserControl DataContext="{RelativeSource Self}">
work?
- 做这样的事情最好的方法是什么?
对于第一个,请尝试:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
对于第二个问题,我认为使用ElementName
or AncestorBinding
是最好的绑定方式UserControl
的属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)