抛出XamlParseException调用XamlReader.Load

kiw*_*pom 3 wpf xaml .net-4.0

我正在玩.net 4 System.Windows.Markup.XamlReader- 就像教育练习一样 - 我一直在遇到同样的问题:如果根对象定义了一个,那么加载xaml XamlReader.Load会抛出a ,但如果没有,则成功解析并加载节点.XamlParseExceptionx:Class

这是我正在尝试的代码:

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...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试XamlReader.Parse直接从持有xaml的字符串中得到相同的结果:只有在没有定义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(或者确实,如果需要)?

有线索吗?

Joh*_*wen 6

XamlReader是一个解析器,而不是编译器,因此不支持代码隐藏.如果您需要将代码与动态加载的XAML相关联,您可以执行类似的操作,例如将其包装到其他地方定义的控件中,您可以使用XAML中的实例,或者在读取XAML后,连接代码(即事件处理程序) )到结果对象中的元素.


Kis*_*mar 5

您不能在动态XAML中使用x:Class.相反,你可以做的是你可以在加载XAML后挂钩事件.请看一下这个链接

通过运行时加载XAML XML?