WPF MessageBox窗口样式

问题描述 投票:39回答:5

如何将默认Windows样式应用于WPF中的标准MessageBox

例如,当我执行下一个代码时:

MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButton.OKCancel, 
    MessageBoxImage.Exclamation);

我收到消息框:

但是在WinForms中,风格一切都很好:

MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButtons.OKCancel, 
    MessageBoxIcon.Exclamation);

c# wpf messagebox
5个回答
57
投票

根据this页面,WPF为一些控件选择旧样式。

要摆脱它,你必须创建一个自定义app.manifest文件(添加 - >新项 - >应用程序清单文件)并粘贴以下代码(在/ trustInfo - 标签之后):

<!-- Activate Windows Common Controls v6 usage (XP and Vista): -->
  <dependency>
  <dependentAssembly>
    <assemblyIdentity
      type="win32"
      name="Microsoft.Windows.Common-Controls"
      version="6.0.0.0"
      processorArchitecture="*"
      publicKeyToken="6595b64144ccf1df"
      language="*"
    />
  </dependentAssembly>
</dependency>

然后你必须用这个app.manifest编译你的解决方案(在项目属性中设置它 - >应用程序 - >指向“图标和清单”中的新清单)。

如果你现在启动你的应用程序,它应该看起来像WinForms- MessageBox。


6
投票

WinForms工作方式的原因是因为在其Main函数中打开了视觉样式(即使用Common Controls v6)。如果你删除对System.Windows.Forms.Application.EnableVisualStyles()的调用,那么WinForms消息框看起来就像WPF一样。

WPF应用程序不会发生这种情况,可能是因为所有WPF控件都已呈现,因此无需使用新版本的Common Control。

您可以尝试在WPF应用程序启动时的某个地方调用EnableVisualStyles()。我不知道它是否会起作用,但值得一试。但是,这需要引用System.Windows.Forms。


6
投票

此外,对于WPF,我建议使用具有Extended WPF ToolkitWPF messagebox


2
投票

就像我如何触发它一样,“重定向”通常对Forms表达的引用(它们的工作方式相同,但命名方式不同):

using MessageBox = System.Windows.Forms.MessageBox;
using MessageBoxImage = System.Windows.Forms.MessageBoxIcon;
using MessageBoxButton = System.Windows.Forms.MessageBoxButtons;
using MessageBoxResult = System.Windows.Forms.DialogResult;

namespace ... class ...

    public MainWindow()
    {
        InitializeComponent();

        System.Windows.Forms.Application.EnableVisualStyles();
    }

    public void do()
    {
        // updated style, but good syntax for a later solution
        MessageBox.Show("Some Message", "DEBUG", MessageBoxButton.OK, MessageBoxImage.Question);
    }

......清单解决方案对我不起作用。


1
投票

创建一个新清单并粘贴:

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
    </application>
  </compatibility>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
      type="win32"
      name="Microsoft.Windows.Common-Controls"
      version="6.0.0.0"
      processorArchitecture="*"
      publicKeyToken="6595b64144ccf1df"
      language="*"
    />
    </dependentAssembly>
  </dependency>
</assembly>
© www.soinside.com 2019 - 2024. All rights reserved.