简体   繁体   中英

Why does a UserControl cause a Serialization error?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM