Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Message Box in WPF XAML

0.00/5 (No votes)
1 Mar 2016 1  
Create Custom Message Box in WPF XAML

Introduction

This tip will demonstrate how to create a custom message box in WPF.

Background

We always face an issue about how we can customize a traditional message box in WPF. Here, we are going to create our own custom message box in WPF.

Using the Code

Step 1

First of all, we need to create a window with the name of 'WpfMessageBox' and create its design like below:

<Window x:Class="MySample.WpfMessageBox"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="WpfMessageBox"  MinHeight="160" 

        MinWidth="420" MaxHeight="750" MaxWidth="750" 

     Background="Transparent" 

     SizeToContent="WidthAndHeight" 

     WindowStartupLocation="CenterScreen"  

     ShowInTaskbar="False" ResizeMode="NoResize" 

     WindowStyle="None" Topmost="True">
    <Border  BorderBrush="LightSlateGray" 

    BorderThickness="0" CornerRadius="0">
        <Grid  >
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Rectangle Grid.Row="1" Grid.Column="0" 

            Grid.RowSpan="2" Grid.ColumnSpan="2">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" 

                    EndPoint="0,1" Opacity="0.8">
                        <GradientStop Color="#70A4B9" 

                        Offset="0.0"/>
                        <GradientStop Color="#CDDFE9" 

                        Offset="1.0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
            <Rectangle Grid.Row="0" 

            Grid.Column="0"  Grid.ColumnSpan="2">
                <Rectangle.Fill>
                    <LinearGradientBrush StartPoint="0,0" 

                    EndPoint="0,1" Opacity="0.5">
                        <GradientStop Color="#26508A" 

                        Offset="0.0"/>
                        <GradientStop Color="#2A739E" 

                        Offset="1.0"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
            <Grid Grid.Row="0" Grid.ColumnSpan="2" 

            MinHeight="40" >
                <TextBlock Margin="5,1,0,1" Name="MessageTitle"  

                FontWeight="Bold" TextTrimming="CharacterEllipsis" 

                LineHeight="22" FontSize="16" 

                VerticalAlignment="Center" Foreground="White"/>
            </Grid>
            <Image Name="img" Margin="5" Grid.Row="1" 

            Grid.Column="0" Width="50" 

            Height="50"  Stretch="Fill" />
            <TextBlock Margin="10,5,10,5"   

            VerticalAlignment="Center" 

            TextWrapping="Wrap" Name="txtMsg" 

            Grid.Row="1" 

                    Grid.Column="1" FontSize="14" 

                    LineHeight="20"  />
            <Grid Grid.Row="2" Grid.ColumnSpan="2"  

            Grid.Column="0" >
                <StackPanel Orientation="Horizontal"  

                HorizontalAlignment="Right" >

                    <Button Name="btnOk" Content="OK" 

                    Margin="3,5" MinWidth="70" Height="35"  

                    Click="Button_Click" Foreground="Black" 

                    FontSize="14" 

                            Style="{StaticResource MessageBoxButtonStyle}"     

                            Background="#b6dbd6" VerticalAlignment="Center" 

                            HorizontalAlignment="Stretch"  

                            VerticalContentAlignment="Center" 

                            HorizontalContentAlignment="Center" />
                    <Button Name="btnYes" Content="Yes"  

                    Margin="3,5" MinWidth="70" Height="35" 

                    Click="Button_Click" Foreground="Black" FontSize="14" 

                            Style="{StaticResource MessageBoxButtonStyle}"    

                            Background="#b6dbd6" VerticalAlignment="Center" 

                            HorizontalAlignment="Stretch"  

                            VerticalContentAlignment="Center" 

                            HorizontalContentAlignment="Center"/>
                    <Button Name="btnNo" Content="No"  

                    Margin="3,5" MinWidth="70" Height="35" 

                    Click="Button_Click" Foreground="Black" 

                    FontSize="14" 

                              Style="{StaticResource MessageBoxButtonStyle}"   

                              Background="#dbb6b6" VerticalAlignment="Center" 

                              HorizontalAlignment="Stretch"  

                              VerticalContentAlignment="Center" 

                              HorizontalContentAlignment="Center" />
                    <Button Name="btnCancel" Margin="3,5" 

                    Content="Cancel" MinWidth="70" 

                    Height="35" Click="Button_Click"

                                Style="{StaticResource MessageBoxButtonStyle}" 

                                Foreground="Black" 

                                Background="#dbb6b6" FontSize="14" 

                                VerticalAlignment="Center" 

                                HorizontalAlignment="Stretch" 

                                VerticalContentAlignment="Center" 

                                HorizontalContentAlignment="Center"/>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

Step 2

Create 'MessageBoxButtonStyle' in your stylesheet file like given below:

<Style TargetType="Button" 

x:Key="MessageBoxButtonStyle">
        <Setter Property="Background" 

        Value="Transparent" />
        <Setter Property="TextBlock.TextAlignment" 

        Value="Center" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border  Name="Border" CornerRadius="0"  

                    BorderBrush="#000" BorderThickness="1,1,1,1" 

                    Background="{TemplateBinding Background}">
                        <ContentPresenter x:Name="contentPresenter" 

                        ContentTemplate="{TemplateBinding ContentTemplate}" 

                        Content="{TemplateBinding Content}" 

                        HorizontalAlignment="{TemplateBinding HorizontalAlignment}" 

                        Margin="{TemplateBinding Padding}" 

                        VerticalAlignment="{TemplateBinding VerticalAlignment}" />
                   </Border>                  
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Step 3

Create the below enums for message box:

public enum MessageBoxType
   {
       ConfirmationWithYesNo = 0,
       ConfirmationWithYesNoCancel,
       Information,
       Error,
       Warning
   }

   public enum MessageBoxImage
   {
       Warning = 0,
       Question,
       Information,
       Error,
       None
   }

Step 4

Write the below code in your WpfMessageBox.cs file:

public partial class WpfMessageBox : Window
    {
        private WpfMessageBox()
        {
            InitializeComponent();
        }
        static WpfMessageBox _messageBox;
        static MessageBoxResult _result = MessageBoxResult.No;
        public static MessageBoxResult Show
        (string caption, string msg, MessageBoxType type)
        {
            switch (type)
            {
                case MessageBoxType.ConfirmationWithYesNo:
                    return Show(caption, msg, MessageBoxButton.YesNo, 
                    MessageBoxImage.Question);
                case MessageBoxType.ConfirmationWithYesNoCancel:
                    return Show(caption, msg, MessageBoxButton.YesNoCancel, 
                    MessageBoxImage.Question);
                case MessageBoxType.Information:
                    return Show(caption, msg, MessageBoxButton.OK, 
                    MessageBoxImage.Information);
                case MessageBoxType.Error:
                    return Show(caption, msg, MessageBoxButton.OK, 
                    MessageBoxImage.Error);
                case MessageBoxType.Warning:
                    return Show(caption, msg, MessageBoxButton.OK, 
                    MessageBoxImage.Warning);
                default:
                    return MessageBoxResult.No;
            }
        }
        public static MessageBoxResult Show(string msg, MessageBoxType type)
        {
            return Show(string.Empty, msg, type);
        }
        public static MessageBoxResult Show(string msg)
        {
            return Show(string.Empty, msg, 
            MessageBoxButton.OK, MessageBoxImage.None);
        }
        public static MessageBoxResult Show
        (string caption, string text)
        {
            return Show(caption, text, 
            MessageBoxButton.OK, MessageBoxImage.None);
        }
        public static MessageBoxResult Show
        (string caption, string text, MessageBoxButton button)
        {
            return Show(caption, text, button, 
            MessageBoxImage.None);
        }
        public static MessageBoxResult Show
        (string caption, string text, 
        MessageBoxButton button, MessageBoxImage image)
        {
            _messageBox = new WpfMessageBox 
            {txtMsg = {Text = text}, MessageTitle = {Text = caption}};
            SetVisibilityOfButtons(button);
            SetImageOfMessageBox(image);
            _messageBox.ShowDialog();
            return _result;
        }
        private static void SetVisibilityOfButtons(MessageBoxButton button)
        {
            switch (button)
            {
                case MessageBoxButton.OK:
                    _messageBox.btnCancel.Visibility = Visibility.Collapsed;
                    _messageBox.btnNo.Visibility = Visibility.Collapsed;
                    _messageBox.btnYes.Visibility = Visibility.Collapsed;
                    _messageBox.btnOk.Focus();
                    break;
                case MessageBoxButton.OKCancel:
                    _messageBox.btnNo.Visibility = Visibility.Collapsed;
                    _messageBox.btnYes.Visibility = Visibility.Collapsed;
                    _messageBox.btnCancel.Focus();
                    break;
                case MessageBoxButton.YesNo:
                    _messageBox.btnOk.Visibility = Visibility.Collapsed;
                    _messageBox.btnCancel.Visibility = Visibility.Collapsed;
                    _messageBox.btnNo.Focus();
                    break;
                case MessageBoxButton.YesNoCancel:
                    _messageBox.btnOk.Visibility = Visibility.Collapsed;
                    _messageBox.btnCancel.Focus();
                    break;
                default:
                    break;
            }
        }
        private static void SetImageOfMessageBox(MessageBoxImage image)
        {
            switch (image)
            {
                case MessageBoxImage.Warning:
                    _messageBox.SetImage("Warning.png");
                    break;
                case MessageBoxImage.Question:
                    _messageBox.SetImage("Question.png");
                    break;
                case MessageBoxImage.Information:
                    _messageBox.SetImage("Information.png");
                    break;
                case MessageBoxImage.Error:
                    _messageBox.SetImage("Error.png");
                    break;
                default:
                    _messageBox.img.Visibility = Visibility.Collapsed;
                    break;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == btnOk)
                _result = MessageBoxResult.OK;
            else if (sender == btnYes)
                _result = MessageBoxResult.Yes;
            else if (sender == btnNo)
                _result = MessageBoxResult.No;
            else if (sender == btnCancel)
                _result = MessageBoxResult.Cancel;
            else
                _result = MessageBoxResult.None;
            _messageBox.Close();
            _messageBox = null;
        }
        private void SetImage(string imageName)
        {
            string uri = string.Format("/Resources/images/{0}", imageName);
            var uriSource = new Uri(uri, UriKind.RelativeOrAbsolute);
            img.Source = new BitmapImage(uriSource);
        }
    }

Now your WPF message box is ready and you can use it like given below:

var messageBoxResult = WpfMessageBox.Show
("Message Box Title","Are you sure?", 
MessageBoxButton.YesNo, MessageBoxImage.Warning);

        if (messageBoxResult != MessageBoxResult.Yes) return;

In 'messageBoxResult' variable, you will get return result from message box.

Note: You need to put image files you own that are being used on messagebox for warning/Question/information/error.

You can modify its code and style as per your requirement.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here