WPF 从Main入口启动窗口时需手动引用 App中的资源
App.Xaml
<Application
x:Class="MySqlDemo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/DN.Controls;component/Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
MainEntry.cs
public static class MainEntry
{
public static event EventHandler OnLoadDataEvent;
[STAThread]
static void Main(string[] args)
{
try
{
App myApp = new App();
System.Windows.Application.LoadComponent(myApp, new System.Uri("App.xaml", System.UriKind.Relative));
myApp.Run(new MainWindow());
}
catch(Exception e)
{
MainEntry.HandledException(e);
}
}
private static void HandledException(Exception e)
{
MessageBox.Show(e.Message);
}
}
原理
从Main入口启动项目时,由于手动创建App对象,再运行窗口,此时App类本身不会去反序列化App.xaml资源,因此,手动创建App对象时,要在运行窗口 前 加载App.xaml。
Application.LoadComponent(myApp, new Uri("App.xaml", UriKind.Relative));