WPF INotifyPropertyChanged用于链接的只读属性 [英] WPF INotifyPropertyChanged for linked read-only properties

查看:68
本文介绍了WPF INotifyPropertyChanged用于链接的只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个依赖于另一个属性的只读属性,那么我试图了解如何更新UI,以便对一个属性的更改会更新两个UI元素(在这种情况下,是一个文本框和一个只读文本框)例如:

I am trying to understand how to update the UI if I have a read-only property that is dependent on another property, so that changes to one property update both UI elements (in this case a textbox and a read-only textbox. For example:

public class raz : INotifyPropertyChanged
{

  int _foo;
  public int foo
  {
    get
    {
      return _foo;
    }
    set
    {
      _foo = value;
      onPropertyChanged(this, "foo");
    }
  }

  public int bar
  {
    get
    {
      return foo*foo;
    }
  }

  public raz()
  {

  }

  public event PropertyChangedEventHandler PropertyChanged;
  private void onPropertyChanged(object sender, string propertyName)
  {
    if(this.PropertyChanged != null)
    {
      PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
    }
  }
}

我的理解是,修改foo后,bar不会自动更新UI.正确的方法是什么?

My understanding is that bar will not automatically update the UI when foo is modified. Whats the correct way to do this?

推荐答案

一种指示柱已更改的方法是在foo设置器中添加对onPropertyChanged(this, "bar")的调用.我知道地狱般的丑陋,但是在那里.

One way to indicate that bar has changed is to add a call to onPropertyChanged(this, "bar") in the foo setter. Ugly as hell, I know, but there you have it.

如果foo是在祖先类中定义的,否则您将无法访问setter的实现,我想您可以订阅PropertyChanged事件,以便在看到"foo"更改时也可以触发栏"更改通知.在您自己的对象实例上订阅事件同样很丑陋,但可以完成工作.

If foo is defined in an ancestor class or you otherwise don't have access to the implementation of the setter, I suppose you could subscribe to the PropertyChanged event so that when you see a "foo" change, you can also fire a "bar" change notification. Subscribing to events on your own object instance is equally ugly, but will get the job done.

这篇关于WPF INotifyPropertyChanged用于链接的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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