当 wpf 中的静态属性更改时收到通知 [英] Get notified when static property changes in wpf

查看:49
本文介绍了当 wpf 中的静态属性更改时收到通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处 微软描述了在 wpf 4.5 中,我们也可以将 INotifypropertyChanged 用于静态属性.所以我尝试这样做.

Here microsoft described that in wpf 4.5 we can use INotifypropertyChanged for static properties as well. So I tried to do that.

代码如下:

public static event PropertyChangedEventHandler StaticPropertyChanged;
    protected static void OnStaticPropertyChanged(string PropertyName)
    {
        PropertyChangedEventHandler handler = StaticPropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(PropertyName));
        }
    }

但是我不知道用什么来代替上面代码中的 this 关键字?

But I dont know what to use instead of this keyword in the above code?

这是我的代码:

public static event PropertyChangedEventHandler StaticPropertyChanged;
protected static void OnStaticPropertyChanged(string PropertyName)
{
    PropertyChangedEventHandler handler = StaticPropertyChanged;
    if (handler != null)
    {
        handler(typeof(MainWindowViewModel), new PropertyChangedEventArgs(PropertyName));
    }
}

private static Haemogram _cHaemogram;
public static Haemogram cHaemogram
{
    get
    {
        return _cHaemogram;
    }
    set
    {
        _cHaemogram = value;
        OnStaticPropertyChanged("cHaemogram");
    }
}

推荐答案

认为您已将此添加到您的视图模型中:

Think that you added this to your viewmodel :

  yourClass.StaticPropertyChanged+= yourClassStaticPropertyChanged;

...

  void yourClassStaticPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {

        }

this"关键字指的是对象发送者"参数.如果在创建处理程序时在代码中使用this",它会在 yourClassStaticPropertyChanged 函数中引用sender".如果发送 null,则 sender 参数将为 null.

The "this" keyword refers the "object sender" parameter. If you use "this" in your code while creating handler, it refers "sender" in yourClassStaticPropertyChanged function. If you send null, the sender parameter will be null.

--编辑--

如果您想更改文本框,请将此代码添加到您的视图模型中:

If you want to get changes to the textbox add this code to your viewmodel :

private string _updatedText;
public string UpdatedText
{
  get
  {
      return _updatedText;
  }
  set
  {
      _updatedText= value;
      OnStaticPropertyChanged("UpdatedText")
  }
}

并在事件中设置 UpdatedText :

And set UpdatedText in the event :

void yourClassStaticPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
                UpdatedText=e.NewValue;
        }

然后像这样将 UpdatedText 绑定到您的文本框:

then bind the UpdatedText to your textbox like this :

<TextBlock Text="{Binding UpdatedText}"/>

这篇关于当 wpf 中的静态属性更改时收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆