如何在 WPF C# 中的代码隐藏(没有 XAML)中创建自定义消息框(对话框)? 我用谷歌搜索了一下,似乎没有找到解决方案。我想要一个带有图像和其他控件的消息框添加到其中。
您可以使用此解决方案:
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);
查看this文章,如果需要,您可以将自定义对话框段落中的所有 Xaml 重新编码为纯 C#。
或者您可以创建自己的窗口并使用
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() 调用的新窗口
我已经实现了一个 WPF MessageBox,它具有与普通接口完全相同的界面,并且还可以通过标准 WPF 控件模板完全自定义:
特点