Why does a UserControl cause a Serialization error?

爱⌒轻易说出口 提交于 2019-12-25 05:24:06

问题


I have the following ComboBox in my MainWindow.xaml:

<ComboBox ItemsSource="{Binding ComboItemsProperty}" />

In MainWindow.xaml.cs:

ObservableCollection<string> ComboItemsField = 
    new ObservableCollection<string>();
public ObservableCollection<string> ComboItemsProperty
{
    get { return ComboItemsField; }
    set { ComboItemsField = value; }
}

This works perfectly! I can add items to the Property and successfully Serialize the ComboBox Element.

My question is, why is it when I have this EXACT code in a UserControl.xaml and UserControl.xaml.cs, I get the following error on attempting to Serialize the control:

Cannot serialize a generic type 'System.Collections.ObjectModel.ObservaleCollection'1[System.String]'

Any thoughts?


回答1:


You don't say how you are "successfully Serializ(ing) the ComboBox Element", but the error is the expected behaviour for UserControls.

XamlWriter (which I assume you're using) cannot serialise bindings, meaning that it will attempt to serialise the actual values bound instead. Since you have a generic collection bound, it fails because XamlWriter cannot serialise generics.

You have two options: Tell XamlWriter that you don't want to serialise the property:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ObservableCollection<string> ComboItemsProperty
{
    get { return ComboItemsField; }
    set { ComboItemsField = value; }
}

or if you do require the items to be bound, then remove the generics problem by creating your own concrete class that derives from the generic. See this question for details.



来源:https://stackoverflow.com/questions/12265981/why-does-a-usercontrol-cause-a-serialization-error

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