我试图将窗口标题绑定到自定义类的属性值。问题是当属性更新时,窗口标题没有更新。
自定义类:
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”)。
1条答案
按热度按时间evrscar21#
您需要通知绑定机制,计算属性
Title
可能已更改,需要重新计算。AddCurrentFileName与IsUnsaved得设置器.
顺便说一句:代码中的
PropertyChanged?.Invoke(this, new(nameof(_isUnsaved)));
是错误的;它必须是PropertyChanged?.Invoke(this, new(nameof(IsUnsaved)));