Aligoglos
Aligoglos

Reputation: 93

How To execute Xaml RunTime

I have xaml code in file and want to read file in runtime and executed this

or have textbox control in my form and write xaml code to textbox and press

button this xaml code executed.

this is possible?

thanks.

Upvotes: 2

Views: 565

Answers (1)

Code0987
Code0987

Reputation: 2618

Here are some static methods for serialization of XAML objects. You just need to use XamlSerializer.Deserialize(string) to make XAML object at runtime from valid XAML text.

Code :

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));
    }
}

Upvotes: 2

Related Questions