views:

268

answers:

1

I'm trying to bind my window title to a property in my view model, like so:

Title="{Binding WindowTitle}"

The property looks like this:

    /// <summary>
    /// The window title (based on profile name)
    /// </summary>
    public string WindowTitle
    {
        get { return CurrentProfileName + " - Backup"; }
    }

The CurrentProfileName property is derived from another property (CurrentProfilePath) that is set whenever someone opens or saves profile. On initial startup, the window title is set properly, but when ever the CurrentProfilePath property changes, the change doesn't bubble up to the window title like I expected it would.

I don't think I can use a dependency property here because the property is a derived one. The base property from which it is derived is a dependency property, but that doesn't seem to have any effect.

How can I make the form title self-updating based on this property?

+3  A: 

That's because WPF has no way of knowing that WindowTitle depends on CurrentProfileName. Your class needs to implement INotifyPropertyChanged, and when you change the value of CurrentProfileName, you need to raise the PropertyChanged event for CurrentProfileName and WindowTitle

private string _currentProfileName;
public string CurrentProfileName
{
    get { return __currentProfileName; }
    set
    {
        _currentProfileName = value;
        OnPropertyChanged("CurrentProfileName");
        OnPropertyChanged("WindowTitle");
    }
}


UPDATE

Here's a typical implementation of INotifyPropertyChanged :

public class MyClass : INotifyPropertyChanged
{
    // The event declared in the interface
    public event PropertyChangedEventHandler PropertyChanged;

    // Helper method to raise the event
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName);
    }

    ...
}
Thomas Levesque
Bingo. That did it. Secondary question - the existing OnPropertyChanged method only accepted a DependencyProperty object - is it really necessary to add the actual PropertyChanged event and a custom OnPropertyChanged method to my class or is there an easier way?
Chris
Yes, you need to declare the event. The existing `OnPropertyChanged` method is inherited from `DependencyObject` and it is only for dependency properties.
Thomas Levesque
See my updated answer for a code sample
Thomas Levesque
Yeah I ended up doing exactly what your second sample shows. I was just wondering if I was taking the long route. Thanks!
Chris