我與.NET 4的System.Windows.Markup.XamlReader
玩耍 - 只是作爲一個教育運動 - ,我不斷碰到了同樣的問題:與XamlReader.Load
加載XAML拋出一個XamlParseException
如果根對象定義x:Class
,但是如果不成功則成功解析並加載節點。XamlParseException拋出調用XamlReader.Load
這裏是我想要的代碼:我從一個字符串持有XAML同樣的結果嘗試XamlReader.Parse
直接
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...
}
}
}
:類聲明中定義:僅如果沒有X的工作。
卸下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
(或者確實如果需要的話)?
任何線索?