1

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

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() 来设置这两个属性时,不会引发通知事件。(这是为了做一个绑定)

有人有想法吗?

非常感谢,

此致,

尼克修斯

4

2 回答 2

2

你其实并没有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 属于哪里,您的虚拟机看起来如何)。

或者,如果您需要一个实例,您可以通过 x:Static 进行绑定 - 并向您的班级公开一个“实例” - 通过“单例” - 例如 CParameters.Instance

例如

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

虽然我建议通过您的视图模型层次结构进行正确的绑定。

注意:
1) 如此典型的 INotifyPropertChanged 实现
2) 添加Singleton' implementation - which is密封的(not required but good),private`ctor(不是必需但推荐) - 和只读静态属性 - 以供外部访问。

于 2013-04-11T19:59:28.233 回答
0
    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));
        }
    }
于 2013-04-11T20:00:22.730 回答