作为 WCF 数据契约的 ObservableCollection 和 CollectionChanged 事件
我将 DataContract 与 ObservableCollection 结合使用:
[DataContract(Namespace = Terms.MyNamespace)]
public class MyContract
{
internal MyContract ()
{
List = new ObservableCollection<string>();
}
[DataMember]
private ObservableCollection<string> list;
[XmlArray("list")]
public ObservableCollection<string> List
{
get
{
return list;
}
set
{
list = value;
list.CollectionChanged += (s, e) =>
{
Console.WriteLine("It is never happens!! Why?");
};
}
}
...
所以,当我像这样处理我的集合时。
MyContract contract = new MyContract();
contract.List.Add("some");
项目已添加,但 CollectionChanged 事件未触发。
为什么?
I use DataContract with ObservableCollection:
[DataContract(Namespace = Terms.MyNamespace)]
public class MyContract
{
internal MyContract ()
{
List = new ObservableCollection<string>();
}
[DataMember]
private ObservableCollection<string> list;
[XmlArray("list")]
public ObservableCollection<string> List
{
get
{
return list;
}
set
{
list = value;
list.CollectionChanged += (s, e) =>
{
Console.WriteLine("It is never happens!! Why?");
};
}
}
...
So, when I work with my collection like this.
MyContract contract = new MyContract();
contract.List.Add("some");
Item was been added but CollectionChanged event not fired.
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您在序列化
list
时没有序列化List
。因此,在反序列化期间,它不会调用列表的setter,因此不会订阅事件。在您的情况下,您可以简单地用DataMemberAttribute
而不是list
标记List
,例如:用法:
在这种情况下,事件将触发。
That is because you don't serialize
List
while serializelist
. So, during deserialization it won't call setter of list, therefore won't subscribe to event. In your case you can simply markList
withDataMemberAttribute
instead oflist
, e.g.:Usage:
In this case event will fire.