问题
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