繁体   English   中英

如何在后面的代码中使用WPF C#创建带有图像的自定义MessageBox?

[英]How to create, in code behind, a Custom MessageBox with Images in WPF C#?

如何在WPF C#中使用背后的代码(没有XAML)创建自定义MessageBox(对话框)? 我用谷歌搜索,似乎找不到解决方案。 我想要一个带有图像和其他控件的MessageBox。

您可以使用以下解决方案:

    string messageBoxText = "Do you want to save changes?";
    string caption = "Your caption";
    MessageBoxButton button = MessageBoxButton.YesNoCancel;
    MessageBoxImage icon = MessageBoxImage.Warning;
    MessageBox.Show(messageBoxText, caption, button, icon);

查看这篇文章,如果需要,您可以将所有Xaml重新编码为“自定义对话框”段落中的纯c#。

或者您可以创建自己的Window并使用MyWindow.ShowDialog()

像下面的代码:

    Window wnd = new Window();
    Grid grid = new Grid();
    wnd.Height = 200;
    wnd.Width = 150;
    grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(100) });
    grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto });
    wnd.Content = grid;
    Image img = new Image();
    Button btn = new Button();
    btn.Content = "OK";
    btn.VerticalAlignment = VerticalAlignment.Bottom;
    Grid.SetRow(img, 0);
    Grid.SetRow(btn, 1); 
    grid.Children.Add(img);
    grid.Children.Add(btn);
    wnd.Owner = MyMainWindow;
    wnd.ShowDialog();

为什么不只在XAML中创建自定义窗口,然后在隐藏代码中使用showDialog()?

XAML中的所有内容都可以用纯c#重写:

<Window>
 <Grid>
  <Grid.ColumnDefinition Width="50" />
  <Grid.ColumnDefinition Width="*">
  <Label Grid.Column="0" Content="Hello World!" />
 </Grid>
</Window>

看起来像这样:

public void MakeWin(DependencyObject owner)
{
   MakeWin(Window.GetWindow(owner));
}

public void MakeWin(Window owner)
{
   Window window = new Window();
   Grid grid = new Grid();
   grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50) });
   grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
   window.Content = grid;

   Label label = new Label { Content = "Hello World!" };
   Grid.SetColumn(label, 0); // Depandency property
   grid.Children.Add(label);

   window.Owner = owner;
   window.ShowDialog();
}

对于图像,WPF工具包中提供了源代码(或预构建的代码), 网址为http://wpftoolkit.codeplex.com/wikipage?title=MessageBox&version=31

如果您需要的不仅仅是图像,一行文本和几个按钮,那么您可能应该只考虑使用通过ShowDialog()调用的新Window

我已经实现了WPF MessageBox,它具有与普通界面完全相同的界面,并且还可以通过标准WPF控件模板完全自定义:

可自定义的WPF消息框

特征

  • WPFMessageBox类具有与当前WPF MessageBox类完全相同的接口。
  • 作为自定义控件实现,因此可以通过标准WPF控件模板完全自定义。
  • 有一个默认控件模板,看起来像标准的MessageBox。
  • 支持所有常见的消息框类型:错误,警告,问题和信息。
  • 具有与打开标准MessageBox时相同的“哔”声。
  • 按Escape按钮时,与标准MessageBox支持相同的行为。
  • 提供与标准MessageBox相同的系统菜单,包括在消息框处于“是-否”模式时禁用“关闭”按钮。
  • 处理从右对齐和从右到左的操作系统,与标准MessageBox相同。
  • 提供支持将所有者窗口设置为WinForms Form控件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM