.NET 9 WPF项目Fluent主题下MessageBox经典样式的解决方法
WPF .NET 9中让MessageBox显示Fluent主题样式的解决办法
原生MessageBox.Show()调用的是Win32经典对话框,不属于WPF可视化树范畴,所以不会自动应用Fluent主题样式。要实现Fluent风格的消息框,有两种可行方案:
方案1:自定义WPF Fluent风格消息框
自己封装一个基于WPF窗口的消息框,确保它继承应用的Fluent主题样式:
using System.Windows; using System.Windows.Controls; public static class FluentMessageBox { public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button = MessageBoxButton.OK) { var dialogWindow = new Window { Title = caption, Width = 420, MinHeight = 180, WindowStyle = WindowStyle.SingleBorderWindow, WindowStartupLocation = WindowStartupLocation.CenterOwner, ResizeMode = ResizeMode.NoResize, // 绑定Fluent主题窗口样式 Style = Application.Current.Resources["FluentWindowStyle"] as Style ?? new Style(typeof(Window)) }; var contentGrid = new Grid { Margin = new Thickness(24) }; var contentStack = new StackPanel { VerticalAlignment = VerticalAlignment.Center }; // 消息文本 var messageBlock = new TextBlock { Text = messageBoxText, FontSize = 14, Margin = new Thickness(0, 0, 0, 20), TextWrapping = TextWrapping.Wrap }; contentStack.Children.Add(messageBlock); // 按钮栏 var buttonPanel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right }; switch (button) { case MessageBoxButton.OK: var okBtn = new Button { Content = "确定", Width = 88, Margin = new Thickness(4) }; okBtn.Click += (s, e) => dialogWindow.DialogResult = true; buttonPanel.Children.Add(okBtn); break; case MessageBoxButton.OKCancel: var cancelBtn = new Button { Content = "取消", Width = 88, Margin = new Thickness(4) }; cancelBtn.Click += (s, e) => dialogWindow.DialogResult = false; buttonPanel.Children.Add(cancelBtn); var okBtn2 = new Button { Content = "确定", Width = 88, Margin = new Thickness(4) }; okBtn2.Click += (s, e) => dialogWindow.DialogResult = true; buttonPanel.Children.Add(okBtn2); break; // 可扩展更多按钮组合 } contentStack.Children.Add(buttonPanel); contentGrid.Children.Add(contentStack); dialogWindow.Content = contentGrid; return dialogWindow.ShowDialog() == true ? MessageBoxResult.OK : MessageBoxResult.Cancel; } }
调用方式替换原有的MessageBox.Show():
FluentMessageBox.Show("操作完成", "提示", MessageBoxButton.OK);
方案2:使用第三方UI库的封装组件
如果不想自己写代码,可以用成熟的WPF UI库,比如MahApps.Metro或MaterialDesignThemes,它们都提供了符合Fluent设计的消息框:
以MahApps.Metro为例:
- 安装NuGet包:
MahApps.Metro - 在窗口中调用异步消息框:
using MahApps.Metro.Controls.Dialogs; // 在窗口类内部调用 var result = await this.ShowMessageAsync("提示", "这是Fluent风格的消息框", MessageDialogStyle.AffirmativeAndNegative);
关键注意点
- 确保你的WPF项目已经正确引用Fluent主题资源字典,在
App.xaml中添加:
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <XamlControlsResources xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
- 彻底弃用原生
MessageBox.Show(),因为它无法适配WPF的主题系统。
内容的提问来源于stack exchange,提问作者Mahdi Ataollahi
相关产品推荐
相关产品推荐

