ObservableCollection and CollectionChanged event as WCF datacontract

て烟熏妆下的殇ゞ 提交于 2019-12-11 02:53:39

问题


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?


回答1:


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?!");
        }
    }
}

Usage:

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.



来源:https://stackoverflow.com/questions/8612633/observablecollection-and-collectionchanged-event-as-wcf-datacontract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!