jcollum
jcollum

Reputation: 46589

databinding to self without code

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.

Upvotes: 1

Views: 252

Answers (1)

Phil Sandler
Phil Sandler

Reputation: 28016

What do you mean by "couldn't get it to work"? You get a binding error, or the text you expected isn't populated?

Assuming the latter, if I had to take a guess, it would be that the Title and Description properties were getting populated after the control is initialized, and don't fire a PropertyChanged event.

Update after comments

You shouldn't need a dependency property, you should just need to implement INotifyProperyChanged. If the initial binding happens before the properties are updated, the view needs to be notified when the update happens.

Have your control implement INotifyPropertyChanged and add the following:

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

Then after Title gets updated:

OnPropertyChanged("Title");

(Same with Description).

Note that I'm still kind of guessing what's going on--post more code if it turns out this isn't the problem.

Upvotes: 1

Related Questions