databinding to self without code

Posted by jcollum on Stack Overflow See other posts from Stack Overflow or by jcollum
Published on 2010-06-17T19:26:00Z Indexed on 2010/06/17 20:43 UTC
Read the original article Hit count: 184

Filed under:
|

I'm building a UserControl in WPF. The control has two properties, Title and Description, that I'd like to bind to two textblocks. Seems real straightforward, and I got it working, but I'm curious about something. To get it to work I had to add this code:

    void CommandBlock_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = this; 
    }

My bindings look like this:

        <TextBlock  Text="{Binding Title}" Width="100" ...  />
        <TextBlock  Text="{Binding Description}" Width="100" ... />

What I'm wondering is how come I couldn't get it to work without the this.DataContext = this; and instead use DataContext="{Binding RelativeSource={RelativeSource Self}}" (in the UserControl element of the markup)? I'm sure I'm missing something about DataContexts but don't know what.

© Stack Overflow or respective owner

Related posts about wpf

Related posts about wpf-binding