WPF - 用于查看模型属性的数据绑定窗口标题

Chr*_*ris 5 data-binding wpf window

我正在尝试将我的窗口标题绑定到我的视图模型中的属性,如下所示:

Title="{Binding WindowTitle}"
Run Code Online (Sandbox Code Playgroud)

该属性如下所示:

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

CurrentProfileName属性派生自另一个属性(CurrentProfilePath),只要有人打开或保存配置文件,该属性就会设置.在初始启动时,窗口标题设置正确,但是当CurrentProfilePath属性发生更改时,更改不会像我预期的那样冒泡到窗口标题.

我不认为我可以在这里使用依赖属性,因为该属性是派生属性.派生它的基本属性是依赖属性,但似乎没有任何影响.

如何根据此属性使表单标题自我更新?

Tho*_*que 9

那是因为WPF无法知道这WindowTitle取决于CurrentProfileName.你的类需要实现INotifyPropertyChanged,当你改变它的值时CurrentProfileName,你需要PropertyChanged提升事件CurrentProfileName WindowTitle

private string _currentProfileName;
public string CurrentProfileName
{
    get { return __currentProfileName; }
    set
    {
        _currentProfileName = value;
        OnPropertyChanged("CurrentProfileName");
        OnPropertyChanged("WindowTitle");
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

这是典型的实现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);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)