WPF标题绑定未更新

2skhul33  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(189)

我试图将窗口标题绑定到自定义类的属性值。问题是当属性更新时,窗口标题没有更新。
自定义类:

public class ObservableWindowTitle : INotifyPropertyChanged
{
    public string AppName { get; }

    private string _currentFileName = string.Empty;
    public string CurrentFileName
    {
        get => _currentFileName;
        set
        {
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (_currentFileName != value)
            {
                _currentFileName = value;
                PropertyChanged?.Invoke(this, new(nameof(CurrentFileName)));
            }
        }
    }

    private bool _isUnsaved = false;
    public bool IsUnsaved
    {
        get => _isUnsaved;
        set
        {
            if (_isUnsaved != value)
            {
                _isUnsaved = value;
                PropertyChanged?.Invoke(this, new(nameof(_isUnsaved)));
            }
        }
    }

    public string Title
    {
        get => string.Format("{0}{1} - {2}",
            (IsUnsaved ? "*" : string.Empty),
            (CurrentFileName.Length == 0 ? "Untitled" : CurrentFileName),
            AppName);
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    public ObservableWindowTitle(string appName) => AppName = appName;
}

窗口标题XAML:

Title="{Binding Path=Title, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"

窗口代码:

public partial class MainWindow : Window
{
    const string fileDialogFilter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
    readonly ILogger<MainWindow> _logger;
    ObservableWindowTitle observableTitle = new((Application.Current.FindResource("AppName") as string)!);

    public MainWindow(ILogger<MainWindow> logger)
    {
        _logger = logger;
        DataContext = observableTitle;

        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        observableTitle.CurrentFileName = "SomeFile";
    }
}

启动应用程序时正确显示标题:“Untitled - SharpNote”(AppName是值为“SharpNote”的静态资源)。但是,单击该按钮时,标题不会更新(应为“SomeFile - SharpNote”)。

evrscar2

evrscar21#

您需要通知绑定机制,计算属性Title可能已更改,需要重新计算。Add

PropertyChanged?.Invoke(this, new(nameof(Title)));

CurrentFileName与IsUnsaved得设置器.
顺便说一句:代码中的PropertyChanged?.Invoke(this, new(nameof(_isUnsaved)));是错误的;它必须是PropertyChanged?.Invoke(this, new(nameof(IsUnsaved)));

相关问题