的ObservableCollection和CollectionChanged事件为WCF datacontract事件、CollectionChanged、ObservableCollection、

2023-09-06 05:18:07 作者:他是我不能拥抱的太阳

我用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.