可以使用MessageBoxOptions类中的DefaultDesktopOnly和MessageBoxOptions枚举中的其他选项来自定义MessageBox的外观和行为。但是,这些选项仅限于更改MessageBox的按钮和图标,而不能更改文本和标题的字体大小和前景色。要更改文本和标题的字体大小和前景色,可以使用自定义MessageBox的方法。

以下是如何创建自定义MessageBox的示例代码:

public static class CustomMessageBox
{
   public static void Show(string message, string caption, int fontSize, Brush foregroundColor)
   {
      var msgBox = new Window();
      msgBox.WindowStyle = WindowStyle.None;
      msgBox.ResizeMode = ResizeMode.NoResize;
      msgBox.Background = Brushes.White;
      msgBox.Width = 400;
      msgBox.Height = 200;
      msgBox.Topmost = true;

      var stackPanel = new StackPanel();
      stackPanel.Margin = new Thickness(10, 20, 10, 10);
      msgBox.Content = stackPanel;

      var textBlock = new TextBlock();
      textBlock.Text = message;
      textBlock.FontSize = fontSize;
      textBlock.Foreground = foregroundColor;
      stackPanel.Children.Add(textBlock);

      var button = new Button();
      button.Content = "OK";
      button.Margin = new Thickness(0, 20, 0, 0);
      button.Width = 75;
      button.Height = 25;
      button.HorizontalAlignment = HorizontalAlignment.Center;
      button.VerticalAlignment = VerticalAlignment.Bottom;
      button.Click += (s, e) => msgBox.Close();
      stackPanel.Children.Add(button);

      msgBox.ShowDialog();
   }
}

使用此自定义MessageBox的示例代码:

CustomMessageBox.Show($"异常原因:《{str}》不能为空!", "开启端口失败", 14, Brushes.Red);

此代码将创建一个自定义MessageBox,其中包含指定的消息和标题,以及指定的字体大小和前景色。此MessageBox将在关闭前禁用父窗口

WPF MessageBoxShow$异常原因:《str》不能为空! 开启端口失败; 怎么把文本和标题字体大小和前景色

原文地址: https://www.cveoy.top/t/topic/cFU9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录