Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - Binding static property and implementing INotifyPropertyChanged

I'm trying to bind a static property of some class to some control. I've tryied a few implementation but each has its problem:

All examples use the next XAML:

 <Label Name="label1" Content="{Binding Path=text}"/>  

1st approach - don't use INotifyPropertyChanged

public class foo1
{
    public static string text { get; set; }
}

The problem is that when 'text' propery changes the control is not notified.

Second approach - use INotifyPropertyChanged

public class foo1 : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private static string _text;
    public static string text
    {
        get { return _text; }
        set
        {
            _text = value;
            OnPropertyChanged("text");
        }
    }
}

This doesn't compile because OnPropertyChanged() method is not static and it's called within a static method.

Second approach try 2: make OnPropertyChanged() method static => this doesn't compile because OnPropertyChanged() is now static and it tries to use 'PropertyChanged' event which is not static.

Second approach try 3: make 'PropertyChanged' event static => this doesn't compile because the class does not implement 'INotifyPropertyChanged.PropertyChanged' event (the event is defined in 'INotifyPropertyChanged interface is not static but here it is static).

At this point I gave up.

Any Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd suggest you just have an instance-property return your static property like this:

private static string _text;
public string text
{
    get { return _text; }
    set
    {
        _text = value;
        OnPropertyChanged("text");
    }
}

However this makes the whole binding comparatively pointless since change notifications are only created in one instance of the class and not every instance. Thus only bindings which bind to the property on the specific instance on which it was changed will update.

A better method would be using a singleton as can be seen here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...