"Wrapping" a BindingList<T> propertry with a List<T> property for serialization.
Posted
by Eric
on Stack Overflow
See other posts from Stack Overflow
or by Eric
Published on 2010-04-14T00:58:29Z
Indexed on
2010/04/14
1:03 UTC
Read the original article
Hit count: 454
I'm writing an app that allows users search and browse catalogs of widgets. My WidgetCatalog
class is serialized and deserialized to and from XML files using DataContractSerializer. My app is working now but I think I can make the code a lot more efficient if I started taking advantage of data binding rather then doing everything manually. Here's a stripped down version of my current WidgetCatalog
class.
[DataContract(Name = "WidgetCatalog")]
class WidgetCatalog
{
[DataContract(Name = "Name")]
public string Name { get; set; }
[DataContract(Name = "Widgets")]
public List<Widget> Widgets { get; set; }
}
I had to write a lot of extra code to keep my UI in sync when widgets are added or removed from a catalog, or their internal properties change. I'm pretty inexperienced with data-binding, but I think I want a BindingList<Widget>
rather than a plain old List<Widget>
. Is this right?
In the past when I had similar needs I found that BindingList<T>
does not serialize very well. Or at least the Event Handers between the items and the list are not serialized. I was using XmlSerializer
though, and DataContractSerializer
may work better.
So I'm thinking of doing something like the code below.
[DataContract(Name = "WidgetCatalog")]
class WidgetCatalog
{
[DataMember(Name = "Name")]
public string Name { get; set; }
[DataMember(Name = "Widgets")]
private List<Widget> WidgetSerializationList
{
get
{
return this._widgetBindingList.ToList<Widget>();
}
set
{
this._widgetBindingList = new BindingList<Widget>(value);
}
}
//these do not get serialized
private BindingList<Widget> _widgetBindingList;
public BindingList<Widget> WidgetBindingList
{
get
{
return this._widgetBindingList;
}
}
public WidgetCatalog()
{
this.WidgetSerializationList = new List<Widget>();
}
}
So I'm serializing a private List<Widget>
property, but the GET
and SET
accessors of the property are reading from, and writing to theBindingList<Widget>
property. Will this even work? It seems like there should be a better way to do this.
© Stack Overflow or respective owner