Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - data binding window title to view model property

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?

like image 345
Chris Avatar asked Oct 02 '09 18:10

Chris


1 Answers

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);
    }

    ...
}
like image 177
Thomas Levesque Avatar answered Oct 03 '22 22:10

Thomas Levesque