Tvd
Tvd

Reputation: 4601

Wpf Binding a TextBlock to App Property's member

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 ??

Upvotes: 1

Views: 1982

Answers (1)

Clemens
Clemens

Reputation: 128060

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; }
    }
}

Upvotes: 3

Related Questions