1

我使用ObservableCollections 作为我的一些绑定的 ItemsSource,并且遇到了我想OnCollectionChanged手动调用以通知绑定引擎应重新检查列表的情况。(BindingList类比是OnListChanged)。

这就是麻烦开始的地方。令人抓狂的是,如果不继承protected这些类型,就不能调用这些方法。Ironpython 支持这一点,但是当我尝试子类化时,它失败了——即使我没有指定任何覆盖方法:

>>> class ObservableCollectionEx(System.Collections.ObjectModel.ObservableCollection):
...     pass
... 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
SystemError: Object reference not set to an instance of an object.

>>> class BindingListEx(System.ComponentModel.BindingList):
...     pass
... 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
SystemError: Object reference not set to an instance of an object.

我要放弃了,我只想打一个该死的电话OnCollectionChanged!帮助!

4

2 回答 2

1

子类化ObservableCollection<T>BindingList<T>都是支持的操作。这是我编写的一个示例,BindingList<T>它公开OnListChanged并且不抛出任何异常

class BindingListEx<T> : BindingList<T>
{
    public void ForceListChanged()
    {
        base.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, 0));
    }
}


class Program
{
    static void Main(string[] args)
    {
        var list = new BindingListEx<int>();
        list.Add(42);
        list.ForceListChanged();
    }
}
于 2011-08-08T17:04:48.760 回答
0

在做了更多研究之后,我找到了一种解决方法。阅读这篇关于从泛型类继承的文章可以了解幕后发生的事情,最值得注意的是这个解释:

封闭构造泛型是用于指代子类是非泛型并且基类被参数化为具体类型的场景的术语。

public class SubClass : BaseClass<int>   {...}

开放构造泛型是用于指代基类和子类都被参数化为泛型类型的场景的术语。

public class SubClass<T> : BaseClass<T> {...}

据此,我在原始帖子中尝试做的(继承自ObservableCollectionsand BindingLists)是第二种形式;试图保持基类和子类参数化。虽然我仍然认为这在 IronPython 中必须以某种方式成为可能,但我无法弄清楚它的语法,所以我现在将满足于第一种形式。并且 whaddaya 知道,它有效:

>>> class BindingListEx(System.ComponentModel.BindingList[str]):
...     pass
... 
>>> 
>>> b = BindingListEx()
>>> b
<BindingListEx object at 0x000000000000002C>
>>> b.Add(3)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: expected str, got int
>>> b.Add("cow")
>>> 

所以在这个例子中,BindingListEx它是非泛型的,并且是作为其参数BindingList输入的参数化基类的子类。str这暂时有效。如果有人弄清楚如何进行 Open Construct 泛型继承(那里的第二种形式),请随时在此处发布,您将得到公认的答案,因为那是我最初的目标。目前,这将不得不做。

于 2011-08-08T18:22:01.897 回答