StaticResource works in design, throws XamlParseException at runtime
This seems so silly, but I've been looking for a couple of hours and nothing I find fixes this problem.
I'm using MvvmLight. I have a simple MainWindow that has nothing in it but a Grid. I hav开发者_开发百科e another class that is a WPF UserControl that contains one button. Both of these have
DataContext="{Binding Main, Source={StaticResource Locator}}"
in their node definition (either Window or UserControl). App.xaml has the standard entry in its Resources:
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
I'm playing with messaging, and I've got a message that says load this UserControl in the MainWindow. I can trace through and everything works just peachy -- right up to the point where it is instantiating the new UserControl and the code behind does its InitializeComponent().
At this point the application stops in the user control's .xaml file with the XamlParseException complaining it cannot find "Locator" (and, yes, I know, resource names are case sensitive, thank you).
This makes absolutely no sense to me. In design mode in the user control, I can navigate to the data context I want -- it sees Locator, and Locator sees Main, and Main sees the property I'm binding to the button. And the designer SHOWS the text on the button.
Anybody???
This is C# in VS 2010 Ultimate, v10.0.30319.1, running in Windows 7.
Well, it does matter about the messaging and the order of that with regard to instantiating the xaml object (e.g., InitializeComponent). In my original code, I was sending the message to load the UserControl from the MainViewModel constructor; this was occurring during the MainWindow's InitializeComponent() call.
Removed the message from the constructor and simply loaded the UserControl in the MainWindow AFTER returning from the InitializeComponent() method. Sure enough, no problem, it worked fine.
So then I added a method to MainViewModel called UIReady() and called that from MainWindow AFTER InitializeComponent() was done. The UIReady() method in MainViewModel simply issues the message to load the UserControl. And it works, no problem. So an extra method to coordinate things, but it accomplishes what I want -- the MainWindow has no idea what UserControl is going to be loaded in it until a ViewModel requests a particular View. Then it loads the UserControl that represents that View.
I don't know enough about all the ends and outs of InitializeComponent, but SOMETHING in there does not like initializing another xaml obect until it finishes its own initialization; it loses touch with things -- like Application Resources.
精彩评论