Search code examples
c#wpfcustom-controlsmessagebox

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


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.


Solution

  • 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();