首页 文章

如何使用xaml和代码序列化序列化wpf用户控件

提问于
浏览
0

我想序列化wpf用户控件xaml和codebehind . XamlWriter.Save() 只序列化's xaml so what can I do in this situation? My situtation is I have a usercontrol which include custom methods, subscribed events (ex: button click) When I deserialize usercontrol (for create usercontrol at runtime) I want to run that events and methods. Sorry my english isn'非常好 .

1 回答

  • 0

    只是一个想法,你可以使用MEF为你的用户控件 Build 一个插件结构 . 您希望动态创建用户控件,但事件处理程序仍应在项目的其他位置进行硬编码;使用插件结构,您可以只收集插件并重用它;事件可以通过命令来处理 . 也许给出一个场景,我们可以找出更多的细节 .

    此外,ISerializable为字段提供了自定义二进制序列化的方法,而不是方法或事件 . 这是一个相关的问题:What is the point of the ISerializable interface?;另一方面,您仍然可以尝试一些模式,例如Web控件如何保存其视图状态;例如两个虚拟方法:

    public virtual byte[] SaveState(); // it saves the states for your custom control
    public virtual void LoadState(byte[] state) // it restore your state back to the control.
    

    自定义代码应该是:

    byte[] state = controlA.SaveState(); // this method saves its own state.
    YourControl controlB = new YourControl();
    controlB.LoadState(state); // this method load the save state from A to B itself.
    

    对于事件,每个事件都有一个处理程序名称,您还可以将其处理程序名称序列化为状态,并通过其命名容器中的已保存名称找回它 . 我没有任何保存方法的经验 .

    如果您仍想保存和加载状态,包括字段,事件和方法,可能序列化不是您正在寻找的正确方法 .

相关问题