的ObservableCollection和CollectionChanged事件为WCF datacontract [英] ObservableCollection and CollectionChanged event as WCF datacontract

查看:162
本文介绍了的ObservableCollection和CollectionChanged事件为WCF datacontract的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用DataContract与的ObservableCollection:

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");

被添加了

项目,但CollectionChanged事件不会激发。

Item was been added but CollectionChanged event not fired.

为什么?

推荐答案

那是因为你不序列化列表同时连载列表。因此,反序列化过程中也不会调用列表的制定者,因此不会订阅事件。你的情况,你可以简单地标记列表 DataMemberAttribute 而不是列表,例如:

That is because you don't serialize List while serialize list. So, during deserialization it won't call setter of list, therefore won't subscribe to event. In your case you can simply mark List with DataMemberAttribute instead of list, e.g.:

[DataContract]
public class MyContract
{
    private ObservableCollection<string> list;

    internal MyContract()
    {
        List = new ObservableCollection<string>();
    }

    [DataMember]
    public ObservableCollection<string> List
    {
        get
        {
            return list;
        }
        private set
        {
            list = value;
            list.CollectionChanged += 
               (s, e) => 
                   Console.WriteLine("It is never happens!! Why? - Are you sure?!");
        }
    }
}

用法:

var obj = new MyContract();

var serializer = new DataContractSerializer(typeof(MyContract));

using (var ms = new MemoryStream())
{
    serializer.WriteObject(ms, obj);

    ms.Seek(0, SeekOrigin.Begin);

    var result = serializer.ReadObject(ms) as MyContract;

    result.List.Add("a");
}

在这种情况下,事件将触发。

In this case event will fire.

这篇关于的ObservableCollection和CollectionChanged事件为WCF datacontract的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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