Wpf Binding a TextBlock to App Property's member

我与影子孤独终老i 提交于 2019-12-23 03:10:06

问题


In my WPF app, I want an object "CaseDetails" to be used globally i.e. by all windows & user controls. CaseDetails implements INotifyPropertyChanged, and has a property 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;

In my App.xaml.cs, I created an object of CaseDetails

public partial class App : Application
{
    private CaseDetails caseDetails;

    public CaseDetails CaseDetails
    {
        get { return this.caseDetails; }
        set { this.caseDetails = value; }
    }

In one of my user control code behind, I create object of CaseDetails and set in App class

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

And the CaseDetails object of App class is updated.

In my MainWindow.xml, I have a TextBlock that is bind to CaseName property of CaseDetails. This Textblock doesn't update. The xml code is :

<TextBlock Name="caseNameTxt" Margin="0, 50, 0, 0" FontWeight="Black" TextAlignment="Left" Width="170" Text="{Binding Path=CaseDetails.CaseName, Source={x:Static Application.Current} }"/>

Why this TextBlock Text poperty is not getting updated ?? Where am I going wrong in Binding ??


回答1:


The binding isn't updated because you are setting the CaseDetails property in your App class, which does not implement INotifyPropertyChanged.

Either you also implement INotifyPropertyChanged in your App class, or you just set properties of the existing CaseDetails instance:

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

The CaseDetails property might then be readonly:

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

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


来源:https://stackoverflow.com/questions/18888937/wpf-binding-a-textblock-to-app-propertys-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!