繁体   English   中英

WPF将TextBlock绑定到App Property的成员

[英]Wpf Binding a TextBlock to App Property's member

在我的WPF应用程序中,我希望对象“ CaseDetails”在全局范围内使用,即由所有Windows和用户控件使用。 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 Name="caseNameTxt" Margin="0, 50, 0, 0" FontWeight="Black" TextAlignment="Left" Width="170" Text="{Binding Path=CaseDetails.CaseName, Source={x:Static Application.Current} }"/>

为什么此TextBlock文本属性未得到更新? 我在绑定哪里出错了?

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

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

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

CaseDetails属性然后可能是只读的:

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

    public CaseDetails CaseDetails
    {
        get { return caseDetails; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM