UserControl's DataContext

svick picture svick · Feb 22, 2011 · Viewed 88.4k times · Source

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 ElementNames, but that doesn't seem like a clean solution to me either.

I have two questions:

  1. Why doesn't <UserControl DataContext="{RelativeSource Self}"> work?
  2. What is the best way to do something like this?

Answer

decyclone picture decyclone · Feb 22, 2011

For first one, try :

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">

And for second question, I think using ElementName or AncestorBinding is best way to bind to UserControl's properties.