Click here to Skip to main content
15,885,767 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Custom Message Box in WPF XAML

Rate me:
Please Sign up or sign in to vote.
2.94/5 (8 votes)
29 Feb 2016CPOL 61K   8   8
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:

XML
<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:

XML
<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:

C#
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:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I am working as Technical Lead having experience more than 8 years. I work in various technologies/frameworks like as - .Net Core, Angular 7/8, CI/CD, C# .net (MVC/Aspx), Web API, Wpf, Angular JS, Entity Framework (Code First), Onion Architecture, IOC, Domain Driven Design, Multi-threading Environment, PHP, Asp Classic, MySql, Ms-Sql etc. I prefer to use Agile Methodology in development process.

Comments and Discussions

 
QuestionGreat Pin
Member 997613625-Jan-24 4:41
Member 997613625-Jan-24 4:41 
QuestionCalling this messagebox from onStartup function..No ui comes up after closing messagebox Pin
Member 1398704215-Oct-19 0:27
Member 1398704215-Oct-19 0:27 
SuggestionNull reference exception Pin
Member 128705128-Mar-18 22:05
Member 128705128-Mar-18 22:05 
GeneralRe: Null reference exception Pin
Shailendra Singh Deol19-Feb-20 7:10
professionalShailendra Singh Deol19-Feb-20 7:10 
QuestionCustom message boxes in wpf mvvm Pin
Member 1359887231-Dec-17 20:17
Member 1359887231-Dec-17 20:17 
PraiseWorked with a charm for me but for beginners' Jut few point to remember Pin
ankitCsharpAsp28-Sep-16 8:13
ankitCsharpAsp28-Sep-16 8:13 
QuestionHelp For Those New to C# Pin
Member 83456182-Mar-16 7:01
Member 83456182-Mar-16 7:01 
It would help if you could put everything together in a format that would directly be accessible from Visual Studio and wold compile. It would assist those of us who are learning and want to study the code. I know that this is very basic and that anyone working in C# should be able to follow your instructions for use, however some of us are really new and are not sure how this should be done. Any help would be appreciated.
TH

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.