UserControl 的 DataContext [英] UserControl's DataContext
问题描述
我正在创建一个 UserControl
我想使用这样的东西:
I'm creating a UserControl
I want to use something like this:
<controls:ColorWithText Color="Red" Text="Red color" />
到目前为止,我已经实现了类似的控件:
So far, I've implemented similar controls like this:
<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
似乎没有必要.
where Color
and Text
are dependency properties of the control defined in code. This works, but specifying ElementName
every time seems unnecessary.
另一个有效的选择是使用
Another option that works is using
<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">
并且没有指定 ElementName
s,但这对我来说似乎也不是一个干净的解决方案.
and not specifying ElementName
s, but that doesn't seem like a clean solution to me either.
我有两个问题:
- 为什么
不起作用? - 做这样的事情最好的方法是什么?
推荐答案
对于第一个,尝试:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
对于第二个问题,我认为使用 ElementName
或 AncestorBinding
是绑定到 UserControl
属性的最佳方式.
And for second question, I think using ElementName
or AncestorBinding
is best way to bind to UserControl
's properties.
这篇关于UserControl 的 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!