从XamlXmlReader - .Net 4写入时,XamlObjectWriter抛出异常

时间:2010-10-02 03:49:03

标签: c# xaml .net-4.0

出于某种原因,我得到了一个例外。 有人可以向我解释为什么以及如何解决这个问题? 我正在尝试阅读DataTemplate。如果有更好的选择请告诉我。 感谢。

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

1 个答案:

答案 0 :(得分:1)

像这样创建XamlXmlReader:

XamlXmlReader reader = new XamlXmlReader(xr, System.Windows.Markup.XamlReader.GetWpfSchemaContext());

并且不要忘记在XAML名称空间声明中使用assembly=。这是访问所必需的 使用XamlXmlReader / Writer API时,您自己的程序集中的类型(Resources)。