views:

40

answers:

1

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.

+1  A: 

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.

Phil Sandler
I think you were right, I added `public static DependencyProperty TitleProperty = DependencyProperty.Register( "Title", typeof(string), typeof(TheUserControl));` and it worked. Still, I thought wpf would be a little smarter about this and not care about when the property was updated, just whether it was.
jcollum
Couldn't get it to work: the properties were set at design time but the values were never populated on the user control.
jcollum
I think you're right... I'm pretty new to WPF but I recall seeing this somewhere. I really thought I'd be able to accomplish this with an attribute decoration on the property.
jcollum