tags:

views:

29

answers:

0

For some reason I get an exception. Can someone please explain to me why and how can fix this? I am trying to read a DataTemplate. If there is a better option please tell. Thanks.

using System;
using System.Windows;
using System.Windows.Data;
using System.IO;
using System.Xaml;
using System.Xml;

namespace TestApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Func("logo", "name");
        }

        public void Func(string img, string name)
        {
            string imgSource = "{Binding Source={x:Static Res:Resources." + img + "}, Converter={StaticResource ImageConverter}}";

            string xamlString =
                "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
                "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" " +
                "xmlns:Res=\"clr-namespace:FavoritesOrganizer.Properties\"><StackPanel>" +
                "<Image Width=\"16\" Height=\"16\" Source=\"" + imgSource + "\" />" +
            "<TextBlock Text=\"" + name + "\" Margin=\"2, 0, 0, 0\" VerticalAlignment=\"Center\" />" +
            "</StackPanel></DataTemplate>";

            StringReader xaml = new StringReader(xamlString);
            XamlXmlWriter xamlWriter = null;
            try
            {
                XmlReader xr = XmlReader.Create(xaml);
                XamlXmlReader reader = new XamlXmlReader(xr);

                XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext);

                XmlWriter xw = XmlWriter.Create(@"d:\xaml.xml");
                xamlWriter = new XamlXmlWriter(xw, reader.SchemaContext);

                int i = 1;
                while (reader.Read())
                {
                    try
                    {
                        var a = reader.Type;
                        xamlWriter.WriteNode(reader);
                        writer.WriteNode(reader);
                        i++;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message + " " + i);
                    }
                }
                DataTemplate datatemplate = (DataTemplate)writer.Result;//.Parse(xaml,pc);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (xamlWriter != null)
                {
                    xamlWriter.Flush();
                    xamlWriter.Close();
                }
            }
        }
    }
}