调用XamlReader.Load时抛出XamlParseException异常

4
我正在尝试使用 .net 4 的 System.Windows.Markup.XamlReader 进行实验,只是为了教育目的,但我一直遇到同样的问题:如果根对象定义了 x:Class,则使用 XamlReader.Load 加载 xaml 会抛出 XamlParseException,但如果没有定义,则可以成功解析和加载节点。

以下是我尝试的代码:

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...
        }
    }
}

我已经尝试过直接使用包含XAML的字符串来调用XamlReader.Parse,但结果相同:只有在未定义x:Class声明时才有效。
删除x:Class声明似乎不是一个好的选择,因为这样会失去代码后台,特别是对InitalizeComponent()的调用。
异常详细信息如下: 'Specified class name 'WpfApplication2.UserControl1' doesn't match actual root instance type 'System.Windows.Controls.UserControl'. Remove the Class directive or provide an instance via XamlObjectWriterSettings.RootObjectInstance.' ...但我不知道如何(在哪里)设置XamlObjectWriterSettings.RootObjectInstance(或者是否需要?)
有什么线索吗?
2个回答

7

XamlReader是一个解析器,不是编译器,因此不支持代码后台。如果您需要将代码与动态加载的XAML关联起来,可以像包装到其他地方定义的控件中那样进行操作,在XAML中使用该控件的实例;或者,在读取XAML后,将代码(即事件处理程序)连接到生成对象中的元素。


5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接