Search code examples
c#.netwpfserializationattached-properties

How to serialize attached properties


I am writing .NET3.5, WPF application using Composite Application Library. Application is divided into several modules.

In infrastructure module I have defined NetworkNode object. The Network module manages a collection of NetworkNodes and uses XmlSerializer to store/load this collection. So far everythings works.

But I have other modules e.g NodeModule. If a NetworkNode was selected in Network module, an event is published to other modules using EventAggregator. These modules can attach various information to the NetworkNode using attached properties.

The problem is the NetworkModule does not know about the other modules, therefor these properties are not serialized. It is possible to somehow list and serialize all properties attached to an object? Or do I have to change the concept and use something else than attached properties?

Regards


Solution

  • You can list all dependency properties (attached or not) defined on an object using DependencyObject.GetLocalValueEnumerator :

        LocalValueEnumerator propEnumerator = foo.GetLocalValueEnumerator();
        while (propEnumerator.MoveNext())
        {
            Console.WriteLine ("{0} = {1}",
                               propEnumerator.Current.Property.Name,
                               propEnumerator.Current.Value);
        }
    

    However, this won't help for XML serialization (unless you implement IXmlSerializable, which is a pain...). You should probably use XamlWriter instead (which I assume is what Drew was talking about, since there is no XamlSerializer...)