Binding static property and implementing INotifyPropertyChanged

前端 未结 3 1223
温柔的废话
温柔的废话 2021-01-06 07:54

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:

3条回答
  •  长发绾君心
    2021-01-06 08:40

    Using a singleton is going to be the easiest and cleanest to implement. If you want to go the hard way without using a singleton you can use the following.

    Create a static PropertyChangedEventHandler that gets called from your static property. When you create a new instance of your class, register to receive a call back from the static event. When you get the callback, call OnPropertyChanged("text"). The BIG problem with this is you need to use a WeakReference when you register for the static event. Otherwise your object will stay around forever. I skipped this step in the code.

    The reason you need to forward to the instance-event is because who ever registered the NotifyPropertyChanged needs to know who the 'sender' (ie the instance of foo1 with the instance-property on it)

    public class foo1 : System.ComponentModel.INotifyPropertyChanged
    {
        // static property
        private static string _text = "static string";
        public static string static_text
        {
            get
            {
                return _text;
            }
            set
            {
                _text = value;
                OnStaticPropertyChanged("static_text");
            }
        }
        private static System.ComponentModel.PropertyChangedEventHandler staticpropChanged;
        static protected void OnStaticPropertyChanged(string pname)
        {
            System.ComponentModel.PropertyChangedEventArgs e = new System.ComponentModel.PropertyChangedEventArgs(pname);
            System.ComponentModel.PropertyChangedEventHandler h = staticpropChanged;
            if (h != null)
                h(null, e);
    
        }
        public foo1()
        {
            // really should use a weakreference here.. but leaving it out
            // for simplicity
            staticpropChanged += foo1_staticpropChanged;
        }
    
        void foo1_staticpropChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            // map the static name to the instance name
            if(e.PropertyName == "static_text") OnPropertyChanged("text");
        }
        // instance-property forwards to static
        public string text
        {
            get { return foo1.static_text; }
            set { foo1.static_text = value; }
        }
    

提交回复
热议问题