【发布时间】:2011-07-01 22:23:51
【问题描述】:
我正在创建一个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>
其中Color 和Text 是代码中定义的控件的依赖属性。这可行,但似乎没有必要每次都指定ElementName。
另一个有效的选项是使用
<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">
并没有指定ElementNames,但这对我来说似乎也不是一个干净的解决方案。
我有两个问题:
- 为什么
<UserControl DataContext="{RelativeSource Self}">不起作用? - 执行此类操作的最佳方法是什么?
【问题讨论】:
标签: wpf xaml datacontext