[英]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控件模板完全自定义:
特征
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.