musefan
musefan

Reputation: 48415

Binding to a property within a static class instance

What I am trying to achieve

I have a WPF application (it's just for testing) and I want to bind the text (Content) of a label to a property somewhere. The idea is that this property value will be changed when the user chooses a different language. When the property changes, I want the label text to update with the new value.

What I have tried

I tried to create a static class with a static property for the label value. For example:

public static class Language
{
    public static string Name = "Name";
}

I then was able to bind this value to my label using XAML like so:

Content="{Binding Source={x:Static lang:Language.Name}}"

And this worked fine for showing the initial value of "Name". The problem is, when the Name property changes the label value doesn't change.

So, back to the drawing board (Google). Then I found this answer which sounded exactly like what I needed. So here was my new attempt at this:

public class Language
{
    public static Language Instance { get; private set; }
    static Language() { Instance = new Language(); }
    private Language() { }

    private string name = "Name";
    public string Name { get { return name; } set { name = value; } }
}

With my binding changed it this:

Content="{Binding Source={x:Static lang:Language.Instance}, Path=Name}"

This still results in the same problem.

Questions

What am I missing here? How can I get the label to update when the value is changed?

Upvotes: 3

Views: 2260

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

That simply isn't a property. Try:

public class Language
{
    public static Language Instance { get; private set; }
    static Language() { Instance = new Language(); }
    private Language() { Name = "Name"; }

    public string Name {get;private set;}
}

or with change notification:

public class Language : INotifyPropertyChanged
{
    public static Language Instance { get; private set; }
    static Language() { Instance = new Language(); }
    private Language() { }

    private string name = "Name";
    public string Name
    {
        get { return name; }
        set { SetValue(ref name, value);}
    }
    protected void SetValue<T>(ref T field, T value,
        [CallerMemberName]string propertyName=null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propertyName);
        }
    }
    protected virtual void OnPropertyChanged(
        [CallerMemberName]string propertyName=null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Upvotes: 4

Related Questions