Serializing Data Objects to XAML (and then dealing with Generics)

A really nice way to handle XML data serialization in WPF is to use the XamlWriter and XamlReader classes. That's right, XAML isn't just for UI (or for WPF for that matter). Basically, you can throw any object at these classes and, assuming you follow a handful of rules (like every class you serialize needs a public, no args constructor), then you end up with a very nice XML representation of that object and you had to do basically no work to get there. I use this approach to serialize business object data all the time. It's super handy.

I consistently run into one issue and just as consistently forget the work around. So as a note to my future self, I thought I should write it down this time. The problem is that XAML has only very limited support for generics. This is a head on collision with the fact that the only thing more convenient than serializing data to XAML is using ObservableCollection<T> for lists of things in those data objects. I use it all over the place, but it doesn't play nicely with XamlWriter.

Fortunately, the fix is easy. XamlWriter doesn't have a problem with the construct of a list at all, it just can't deal with the fact that it's a generic. To work around this, then, we just need to create a proper class that derives from ObservableCollection<T>. So something like this:

                            public Customer { ObservableCollection<Order> Orders; }


                            class OrderCollection : ObservableCollection<Order> { } public Customer { OrderCollection
                                Orders; }

And then your up and running again. I whipped up a little sample app that shows examples of using both XamlReader and XamlWriter to serialize data object to XAML as well as the workaround for ObservableCollection<T>. You can get it from the link below:



Loading... Show