Event NotifyChanged不触发我的静态变量

本文关键字:我的 静态 变量 NotifyChanged Event | 更新日期: 2023-09-27 18:08:47

我创建了一个具有两个静态属性的类:

public class CParametres
{
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
    private  static Color m_ThemeColorGradientBegin;
    public  static Color ThemeColorGradientBegin
    {
        get { return m_ThemeColorGradientBegin; }
        set
        {
            m_ThemeColorGradientBegin = value;
            NotifyStaticPropertyChanged("ThemeColorGradientBegin");
        }
    }
    private  static Color m_ThemeColorGradientEnd;
    public  static Color ThemeColorGradientEnd
    {
        get { return m_ThemeColorGradientEnd; }
        set
        {
            m_ThemeColorGradientEnd = value;
            NotifyStaticPropertyChanged("ThemeColorGradientEnd");
        }
    }
    public CParametres()
    {
     ....   
    }
    public void setThemeGradient(Color ColorBegin, Color ColorEnd)
    {
        ThemeColorGradientBegin = ColorBegin;
        ThemeColorGradientEnd = ColorEnd;
    }
    private static void NotifyStaticPropertyChanged(string propertyName)
    {
        if (StaticPropertyChanged != null)
        {
            StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }
    }
}

我的问题是,当我使用setThemeGradient()来设置这两个属性时,notify事件不会引发。(这是为了做一个绑定)

谁有什么主意?

谢谢你,

最诚挚的问候,

Nixeus

Event NotifyChanged不触发我的静态变量

你实际上没有implement INotifyPropertyChanged

你不能这样做作为static

你应该正确地实现INotifyPropertyChanged -然后绑定到实例的属性。

public sealed class YourClass : INotifyPropertyChanged 
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName) { this.PropertyChanged.Raise(this, new PropertyChangedEventArgs(propertyName)); } // my 'raise' use typical event handling  
    public static readonly YourClass Instance = new YourClass(); // your ctor params if needed
    private YourClass() // ensure only you can 'construct'
    { }
    // call OnPropertyChanged from your properties
    // implement 'non-static' properties

使用你的视图模型来获得正确的实例(我不确定CParameters属于哪里,你的vm看起来像什么)。

或者如果你需要一个实例,你可以通过x:Static - and来绑定将"Instance"暴露给你的类——通过"Singleton"——例如:CParameters.Instance

{Binding Path=Property, Source={x:Static my:YourClass.Instance}}  

尽管我建议通过视图模型层次结构进行适当的绑定。

注意:
1)典型的INotifyPropertChanged实现
2)为外部访问添加Singleton' implementation - which is密封(not required but good),私有变量(不是必需的,但推荐使用)和只读静态属性。

    public event PropertyChangedEventHandler PropertyChanged;
    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null && !String.IsNullOrEmpty(propertyName))
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }