Binding to static property

后端 未结 12 2297
夕颜
夕颜 2020-11-22 05:14

I\'m having a hard time binding a simple static string property to a TextBox.

Here\'s the class with the static property:



        
12条回答
  •  余生分开走
    2020-11-22 05:33

    Another solution is to create a normal class which implements PropertyChanger like this

    public class ViewProps : PropertyChanger
    {
        private string _MyValue = string.Empty;
        public string MyValue
        {
            get { 
                return _MyValue
            }
            set
            {
                if (_MyValue == value)
                {
                    return;
                }
                SetProperty(ref _MyValue, value);
            }
        }
    }
    

    Then create a static instance of the class somewhere you wont

    public class MyClass
    {
        private static ViewProps _ViewProps = null;
        public static ViewProps ViewProps
        {
            get
            {
                if (_ViewProps == null)
                {
                    _ViewProps = new ViewProps();
                }
                return _ViewProps;
            }
        }
    }
    

    And now use it as static property

    
    

    And here is PropertyChanger implementation if necessary

    public abstract class PropertyChanger : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected bool SetProperty(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (object.Equals(storage, value)) return false;
    
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

提交回复
热议问题