C# 在Silverlight中序列化UserControl

C# 在Silverlight中序列化UserControl,c#,silverlight,c#-4.0,silverlight-4.0,C#,Silverlight,C# 4.0,Silverlight 4.0,我想在Silverlight中序列化UserControl。我想做的就是“深度复制”。我尝试了此代码,但它不起作用: using System.Windows; using System.Windows.Controls; using System.Runtime.Serialization; using System.IO; namespace SilverlightApplication1 { public partial class MainPage : UserControl

我想在Silverlight中序列化UserControl。我想做的就是“深度复制”。我尝试了此代码,但它不起作用:

using System.Windows;
using System.Windows.Controls;
using System.Runtime.Serialization;
using System.IO;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(UserControl));
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, this);
            }
        }
    }
}
我得到一个例外:

Type 'System.Windows.UIElement' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
我怎样才能摆脱这个异常


您要问的一个明显的问题是,为什么我要序列化UserControl?原因是,我正在尝试使用Silverlight的打印API。我正在用我的用户控件创建一个WriteableBitmap,然后尝试打印它。然而,我的UserControl有黑色主题,但在打印时它应该是白色的。如果我直接修改UserControl的“背景”,它将影响我在屏幕上的视觉效果,这不是我想要的!因此,我试图在内存中创建usercontrol的克隆,然后在幕后修改它的背景,并用它创建WriteableBitmap并打印它。然而,到现在为止,运气不好

最好的方法是将usercontrol绑定到可序列化对象

因此,您将序列化自定义对象,而不是序列化设计不支持的usercontrol


这也将产生一个更干净、更小的序列化对象。

我想这是不可能的。Silverlight的很大一部分是本机代码。状态的很大一部分在非托管内存中。因此,您将无法使用任何外部序列化程序来获取该状态


唯一可能的方法是通过模板化视图模型来创建打印控件。如果您有一个保持UI重要状态的模型,那么创建控件克隆就很容易了。然后根据需要对它们进行样式设置。

您是否…尝试按照异常消息中给出的说明进行操作?我如何才能做到这一点?UIElement都存在于DLL中。如何将它们标记为可序列化的?您可以将类标记为可序列化的,它不必是基对象。我已经尝试过了。它不起作用,因为UserControl反过来包含各种UIElement,如网格等。要序列化整个图形,这意味着我必须扩展每种类型的对象,并将其标记为序列化,这显然是不可行的。您尝试过吗?我找不到XamlWriter。XamlReader是我唯一能找到的。我遗漏了什么吗?抱歉,不支持。我应该检查一下。