简体   繁体   English

从列表中删除不会呼叫设置器?

[英]Remove from list doen't call setter?

In my c# app (MVVM Pattern) I have something like this: 在我的C#应用​​程序(MVVM模式)中,我有类似以下内容:

 private List<MyClass> _classes= new List<MyClass>();
 public List<MyClass> Classes
    {
        get { return _classes; }
        set
        {
            _servers = value;
            NotifyOfPropertyChange(() => Classes);
            NotifyOfPropertyChange(() => Classes2);
        }
    }
  public List<MyClass> Classes2
    {
        get
        {
           return Classes.Where(class=> class.boolValue).ToList();
        }
    }

And when I use Classes.Add(class) or Classes.Remove(class) setter doesn't called. 当我使用Classes.Add(class)Classes.Remove(class) setter时不会被调用。 Why? 为什么?

Because you aren't changing the Classes property -- you are changing the internal state of the object referenced by Classes . 因为您没有更改Classes属性,所以您正在更改Classes引用的对象的内部状态。 If you need to be notified of changes to the list, you may want to look into ObservableCollection : 如果需要通知您列表的更改,则可能需要查看ObservableCollection

http://msdn.microsoft.com/en-us/library/ms668604.aspx http://msdn.microsoft.com/en-us/library/ms668604.aspx

It is because Classes.Add is not setting the Classes property, it is just calling Get then performing the method on the object that was returned. 这是因为Classes.Add没有设置Classes属性,它只是调用Get然后对返回的对象执行该方法。 You could force your setter to occur by doing the Add() then re-setting the property ( Classes = Classes ) but that's a bit of a cheat. 您可以通过执行Add()然后重新设置属性( Classes = Classes )来强制设置程序发生,但这有点作弊。 Your best bet would be to use an ObservableCollection as graham says, or derive your own list class that overrides the Add method to raise an event. 最好的选择是使用graham所说的ObservableCollection,或者派生自己的列表类,该类重写Add方法以引发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM