开发者

XamlParseException thrown calling XamlReader.Load

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开发者_如何学C, but successfully parses and loads the node if not.

Here's the code I'm trying:

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

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.

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

The exception detail:

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

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

Any clues?


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.


You can't use x:Class in dynamic XAML. Instead what you can do is you can hook events after the loading XAML. please have a look at this link

Loading XAML XML through runtime?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜