为什么 UserControl 会导致序列化错误? [英] Why does a UserControl cause a Serialization error?

查看:25
本文介绍了为什么 UserControl 会导致序列化错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 MainWindow.xaml 中有以下 ComboBox:

I have the following ComboBox in my MainWindow.xaml:

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

在 MainWindow.xaml.cs 中:

In MainWindow.xaml.cs:

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

这很好用!我可以将项目添加到属性并成功序列化 ComboBox 元素.

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

我的问题是,为什么当我在 UserControl.xaml 和 UserControl.xaml.cs 中有这个 EXACT 代码时,在尝试序列化控件时出现以下错误:

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:

无法序列化泛型类型'System.Collections.ObjectModel.ObservaleCollection'1[System.String]'

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

有什么想法吗?

推荐答案

你没有说你是如何成功地将 ComboBox 元素序列化",但错误是 UserControls 的预期行为.

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

XamlWriter(我假设您正在使用)无法序列化绑定,这意味着它将尝试序列化绑定的实际值.由于您绑定了泛型集合,它会失败,因为 XamlWriter 无法序列化泛型.

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.

您有两个选择:告诉 XamlWriter 您不想序列化该属性:

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.

这篇关于为什么 UserControl 会导致序列化错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆