Static binding doesn't update when resource changes

后端 未结 2 1560
慢半拍i
慢半拍i 2020-11-27 08:18

I\'d first like to say I\'m very new to Binding.. I\'ve done some things in WPF already but I never used binding because concept is a bit too hard to understand for me right

相关标签:
2条回答
  • 2020-11-27 08:56

    First of all, your property is actually not a property, but a field. A minimal property declaration would look like this:

    public static SolidColorBrush Property { get; set; }
    

    Please note the name is starting with an uppercase letter, which is a widely accepted coding convention in C#.

    Because you also want to have a change notification fired whenever the value of the property changes, you need to declare a property-changed event (which for non-static properties is usually done by implementing the INotifyPropertyChanged interface).

    For static properties there is a new mechanism in WPF 4.5 (or 4.0?), where you can write a static property changed event and property declaration like this:

    public static class AppStyle
    {
        public static event PropertyChangedEventHandler StaticPropertyChanged;
    
        private static void OnStaticPropertyChanged(string propertyName)
        {
            StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
        }
    
        private static SolidColorBrush property = Brushes.Red; // backing field
    
        public static SolidColorBrush Property
        {
            get { return property; }
            set
            {
                property = value;
                OnStaticPropertyChanged("Property");
            }
        }
    
        public static void ChangeTheme()
        {
            Property = Brushes.Blue;
        }
    }
    

    The binding to a static property would be written with the property path in parentheses:

    Background="{Binding Path=(style:AppStyle.Property)}"          
    
    0 讨论(0)
  • 2020-11-27 08:56

    To implement reaction on a change, you need to notify about the change. See INotifyPropertyChanged interface. However, you can't use it with a static class. What about a singleton (ideally using some dependency injection container) instead of a static class?

    0 讨论(0)
提交回复
热议问题