XamlParseException抛出调用XamlReader.Load [英] XamlParseException thrown calling XamlReader.Load

查看:780
本文介绍了XamlParseException抛出调用XamlReader.Load的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET 4中的 System.Windows.Markup.XamlReader 玩弄与 XamlReader.Load 抛出一个 XamlParseException 如果根对象定义了一个 X:类,但成功地解析和加载节点,如果没有。

I'm playing around with .net 4's System.Windows.Markup.XamlReader - just as an education exercise - and I keep bumping into the same problem: Loading xaml with XamlReader.Load throws a XamlParseException if the root object defines an x:Class, but successfully parses and loads the node if not.

这里的code我想:

using System.Windows;
using System.Xaml;
using XamlReader = System.Windows.Markup.XamlReader;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // Load up UserControl1.xaml from the solution
            var reader = new XamlXmlReader(@"../../UserControl1.xaml", XamlReader.GetWpfSchemaContext());
            var userControl = XamlReader.Load(reader) as UserControl1;

            //  Do something with userControl...
        }
    }
}

我已经试过 XamlReader.Parse 直接从字符串持有同样的结果的XAML:只能如果没有X:类声明定义

I've tried XamlReader.Parse directly from a string holding the xaml with the same result: only works if no x:Class declaration is defined.

删除 X:类声明似乎不是一个好的选择,因为那时我失去了code-落后,特别是呼吁 InitalizeComponent()

Removing the x:Class declaration doesn't seem like a good option, because then I lose the code-behind, specifically the call to InitalizeComponent()

的异常详细信息:

'指定的类名WpfApplication2.UserControl1不符合实际的根实例类型System.Windows.Controls.UserControl。卸下类指令,或通过XamlObjectWriterSettings.RootObjectInstance提供了一个实例。

...但我不知道如何(在哪里)设置 XamlObjectWriterSettings.RootObjectInstance (或实际上,如果这是必需的?)

...but I don't know how (where) to set XamlObjectWriterSettings.RootObjectInstance (or indeed, if that's required?)

任何线索?

推荐答案

的XamlReader是一个分析器,不是一个编译器,因此不支持code-后面。如果你需要与你的动态加载XAML关联code,你可以这样做将其包装成别处定义的控件,您可以在XAML使用的实例或,读了XAML后,连接了code(即事件处理程序),以生成的对象中的元素。

XamlReader is a parser, not a compiler, so doesn't support code-behind. If you need to associate code with your dynamically loaded XAML you can do something like wrapping it up into a control defined elsewhere that you can use an instance of in the XAML or, after reading in the XAML, connect up the code (i.e. event handlers) to elements in the resulting object.

这篇关于XamlParseException抛出调用XamlReader.Load的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆