在 WinForms 中托管时将主题应用于 WPF UserControl

Applying a Theme to a WPF UserControl When Hosted in WinForms

我在 WinForms 应用程序中托管 WPF UserControl(实际上是几个)。

由于 Win7 (Aero)、Win8 (Aero2) 和(我假设)Win10 默认主题之间的视觉差异,我正在尝试指定最低公分母主题 (Aero) 并定制我的 UI 从那里,从而希望避免任何 OS 主题问题。

据我了解,问题有两方面:1) 没有 System.Windows.Application 对象,因为它托管在 WinForms 项目中,所以我必须创建一个;2) 我必须指定主题我要用。

第一点 thanks to this Dr. Wpf blog post 很简单,可以使用 EnsureWpfApplicationResources() 方法解决 (字符串在有助于提高可读性的地方拆分):

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        EnsureWpfApplicationResources();
        AssignWin7Theme();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new myWinForm());
    }

    static void EnsureWpfApplicationResources()
    {
        if (Wpf.Application.Current == null)
        {
            // create the wpf application object
            new Wpf.Application(); // autoassigns to Wpf.Application.Current
        }
    }

    static void AssignWin7Theme()
    {
        Uri uri = new Uri(
            "PresentationFramework.Aero;V4.0.0.0;" +
            "31bf3856ad364e35;component\themes/aero.normalcolor.xaml",
            UriKind.Relative);

        Wpf.Application.Current.Resources.MergedDictionaries.Add(
            Wpf.Application.LoadComponent(uri) as Wpf.ResourceDictionary);
    }
}

我从 this blog post by Eli Arbel 导出的 AssignWin7Theme() 给我带来了麻烦。代码运行良好(没有抛出异常)但我的控件外观在 Win8 上没有改变以匹配我在 Win7 上看到的内容。我认为它应该自动选择这个设置;我需要在每个控件的 XAML 中设置一个属性吗?我还做错了什么?

你应该使用 UriKind.Relative 而不是绝对的。不抛才奇怪

还要注意版本。如果您使用的是 .NET 4.x,它应该是 V4.0.0.0.