如何执行Xaml RunTime

时间:2011-10-23 15:02:10

标签: wpf

我在文件中有xaml代码,想要在运行时读取文件并执行此

或在我的表单中使用文本框控件并将xaml代码写入文本框并按

按钮执行此xaml代码。

这可能吗?

感谢。

1 个答案:

答案 0 :(得分:2)

以下是一些用于序列化XAML对象的静态方法。您只需要使用XamlSerializer.Deserialize(string)在运行时从有效的XAML文本生成XAML对象。

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Xml;
using System.Windows.Markup;
using System.IO;
using System.Windows.Markup.Primitives;
using System.Reflection;

public class XamlSerializer
{   
    static internal string Serialize(object toSerialize)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.NewLineOnAttributes = true;
        settings.ConformanceLevel = ConformanceLevel.Auto;
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb, settings);
        XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer);
        manager.XamlWriterMode = XamlWriterMode.Expression;
        XamlWriter.Save(toSerialize, manager);

        return sb.ToString();
    } 
    static internal object Deserialize(string xamlText)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xamlText);
        return XamlReader.Load(new XmlNodeReader(doc));
    }
}