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>
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">
and not specifying ElementName
s, but that doesn't seem like a clean solution to me either.
I have two questions:
- Why doesn't
<UserControl DataContext="{RelativeSource Self}">
work? - What is the best way to do something like this?