Why are my WPF styles not shown in the designer?
I've created a WPF application using Visual Studio 2010, converted App.xaml to a Page and added a call to InitializeComponent in the constructor. I've then created a new window called "LoginWindow" and added the following to the App.xaml.cs:
[STAThread]
public static void Main()
{
var app = new App();
app.Run(new LoginWindow());
}
Next I added a style to the App.xaml as follows:
<Style x:Key="MyWindowStyle" TargetType="Window">
<Setter Property="Background" Value="Red" />
</Style>
Finally, in the LoginWindow I added the following style reference:
Style="{StaticResource MyWindowStyle}"
When I run the program I see my login window with a red background as expected. However, when I view the window in the designer the style is not applied. The {StaticResource MyWindowStyle} is underline and showing the error, "The resource 'MyWindowStyle' could not be resolved".
Why is this?
EDIT
I got a f开发者_运维问答ix on another question that sorted this one out too. I stopped the app.xaml being a page and used the StartUp even instead of a Main method.
I'm not sure about the reason for your designer problem, but my suggestion would be to go back to the default WPF application template and see if that works.
App.xaml
is an important file and shouldn't be converted to a page (you should add a separate page), and you don't need your Main
method to start the application: in the default app.xaml
file you'll see an attribute that (in a default project) is StartupUri="MainWindow.xaml"
- use that to point to your LoginWindow.xaml
.
I've just tried it in VS using the standard template just to check, and I see no problem. To confirm, all I did was add your style to the (default) app.xaml
file, and apply it to my window in the same way as you - it shows fine in the designer.
The reason that it doesn't show up in the designer is that it only looks in the UserControl/whatever + Any Application named App's XAML. Since you made App.Xaml into a Page the designer cannot know that that is the one the UserControl will be hosted within. At run-time WPF will look in the Page and any Parent it might have (including Parent's Parent and so on).
Instead, Let App.xaml point to a 'dummy'-page that in it's overriden Loaded-event navigates to the right Page with the DataContext set.
精彩评论