【问题标题】:Wpf Binding a TextBlock to App Property's memberWpf将TextBlock绑定到App Property的成员
【发布时间】:2013-09-19 07:45:33
【问题描述】:

在我的 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 中,我有一个绑定到 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 Text 属性没有更新??我在 Binding 中哪里出错了??

【问题讨论】:

    标签: c# wpf binding global textblock


    【解决方案1】:

    绑定未更新,因为您在 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; }
        }
    }
    

    【讨论】:

    • 我尝试将 CaseDetails 设为只读并以这种方式工作,但没有任何区别。最后我尝试在 App 类中实现 INotifyPropertyChanged,这完成了绑定更新。谢谢
    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多