简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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