Wpf将TextBlock绑定到App Property的成员

在我的WPF应用程序中,我希望全局使用对象“CaseDetails”,即所有窗口和用户控件。 CaseDetails实现了INotifyPropertyChanged,并具有属性CaseName。

public class CaseDetails : INotifyPropertyChanged { private string caseName, path, outputPath, inputPath; public CaseDetails() { } public string CaseName { get { return caseName; } set { if (caseName != value) { caseName = value; SetPaths(); OnPropertyChanged("CaseName"); } } } protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; 

在我的App.xaml.cs中,我创建了一个CaseDetails对象

 public partial class App : Application { private CaseDetails caseDetails; public CaseDetails CaseDetails { get { return this.caseDetails; } set { this.caseDetails = value; } } 

在我的一个用户控制代码中,我创建了CaseDetails的对象并在App类中设置

 (Application.Current as App).CaseDetails = caseDetails; 

App类的CaseDetails对象已更新。

在我的MainWindow.xml中,我有一个TextBlock,它绑定到CaseDetails的CaseName属性。 此Textblock不会更新。 xml代码是:

  

为什么这个TextBlock Text属性没有得到更新? 我在哪里遇到绑定?

绑定未更新,因为您在App类中设置了CaseDetails属性,该属性未实现INotifyPropertyChanged。

您也可以在App类中实现INotifyPropertyChanged,或者只设置现有CaseDetails实例的属性:

 (Application.Current as App).CaseDetails.CaseName = caseDetails.CaseName; ... 

CaseDetails属性可能只是readonly:

 public partial class App : Application { private readonly CaseDetails caseDetails = new CaseDetails(); public CaseDetails CaseDetails { get { return caseDetails; } } }