How to create, in code behind (with no XAML), a custom MessageBox (Dialog Boxes) in WPF C#? I googled it and seems not to find a solution. I would want to have a MessageBox with Images and other Controls add to it.
You may use this solution:
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);
look over this article, you my recode all Xaml into pure c# in Custom Dialog Boxes paragraph if you want.
or you may create your own Window and use MyWindow.ShowDialog()
.
Like in this code:
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()?
Everything from XAML can be rewrited in pure c#:
<Window>
<Grid>
<Grid.ColumnDefinition Width="50" />
<Grid.ColumnDefinition Width="*">
<Label Grid.Column="0" Content="Hello World!" />
</Grid>
</Window>
will looks like this:
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();
}
For images, there is source code (or a prebuilt one) for you in the WPF toolkit http://wpftoolkit.codeplex.com/wikipage?title=MessageBox&version=31
If you need more than an image, a line of text and a couple of buttons, then you should probably start looking at just using a new Window invoked with ShowDialog()
I've implemented a WPF MessageBox that has the exact same interface has the normal one and is also fully customizable via standard WPF control templates:
Features
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.