Click here to Skip to main content
Click here to Skip to main content

Message boxes and Confirm dialogs using the Silverlight Toolkit

, 8 Oct 2009
Rate this:
Please Sign up or sign in to vote.
An article demonstrating how to implement a message box or confirm dialog with the Silverlight Toolkit.

SilverlightMessageBox.png

Introduction

This article will show you how to leverage the Silverlight Toolkit's ChildWindow class to implement snazzy looking Message and Confirm dialog boxes.

Although Silverlight already exposes a MessageBox (in the System.Windows namespace), it looks more Windows-like in appearance, and none of the flashy Silverlight 'shine' is present. Also, no Confirm dialog seems to natively exist. What this article will show you is how to implement these dialogs using the Silverlight Toolkit.

Background

When I first started using Silverlight (version 2.0), I was using the built-in MessageBox class to display various bits of information (such as operation success or failure) to the user. This was easy to use, and no extra work was required. However, the look-and-feel did not fit in with the rest of the Silverlight applications I was writing, and the MessageBox really looked more like, well, a Windows message box.

So I replaced this with a user control I wrote, which has a more Silverlight tone to it. Sure, it was a simple implementation, but it had more of a Silverlight ambience to it, and the world seemed a happier, brighter place.

Then, Microsoft released Silverlight 3.0, and a short while after that, I discovered the Silverlight 3.0 Toolkit (the July release, to be exact!). While browsing through what was available in the toolkit, I stumbled across the ChildWindow class. Very nice, I thought, and immediately it screamed "I would work well with a custom MessageBox / Confirm Dialog implementation"!

Using the Code

The attached solution comprises three projects - the Silverlight application demoing the Message Box (FortySixApplesMessageBox), a web application project that hosts the Silverlight application (FortySixApplesMessageBox.Web), and a Silverlight class library containing the Message Box / Confirm Dialog implementation code (FortySixApplesMessageBox.Common).

To run the demo, extract the archive to your local disk, make FortySixApplesMessageBox.Web the startup project, and FortySixApplesMessageBoxTestPage.aspx the startup page. Run the application, and click the "Show Confirm dialog" button to show an example of the dialog.

Below is an example of how to show a confirm dialog:

// This code is called from the constructor in MainPage.xaml.cs
// in the FortySixApplesMessageBox project. 
CreateButton.Click += (sender, args) =>
    {
        var messageBox = new MessageBoxPopUp();
        messageBox.Show(
            "Confirm",
            "This is a demo confirm dialog box. " + 
            "It gives the user a [Yes], [No], or [Cancel] option", 
            Buttons.YesNoCancel);
    };

which produces the following:

SilverlightMessageBox.png

The MessageBox / Confirm Dialog Class

The dialogs have been defined in the FortySixApplesMessageBox.Common class library as the MessageBoxPopUp class.

The first thing to notice is that MessageBoxPopUp inherits from ChildWindow. As mentioned previously, this class is defined in the Silverlight Toolkit, and System.Windows.Controls should be referenced to obtain access to it. What the ChildWindow class provides is the pop up functionality and animation (using the Visual State Manager), as well as ensuring that the rest of the UI is disabled while the window / pop up is active.

OK, so now, we have the basic pop up functionality provided by the ChildWindow class. The next piece in the puzzle is to add Message Box-specific functionality. This includes a way of specifying what buttons the message box is to provide, and a means for the developer to pass in a title for the message box, as well as what message is to be displayed to the user.

The former is exposed as an enum called, wait for it, wait for it, yup, you guessed it - Buttons!

public enum Buttons
{
    Ok,
    YesNo,
    OkCancel,
    YesNoCancel
}

I've made provision for the developer to set certain visual characteristics in two places. Firstly, in the overloaded constructors, and secondly, in the overloaded Show() methods. The developer can specify a width, height, and opacity for the message box pop up. One thing to note here is if a height, width, and opacity is set in one of the message box constructors, and then different values in one of the overloaded Show() methods; the latter will override those set in the constructor.

An example of a constructor that initializes the message box pop up to a specified width and height, looks like this:

public MessageBoxPopUp(double width, double height, double opacity)
{
    InitializeComponent();
    Width = width;
    Height = height;
    Opacity = opacity;
}

To display the message box pop up to the user, the developer can call one of the overloaded Show() methods, as follows:

public void Show(string title, string message, Buttons buttons)
{
    generateButtons(buttons);
    Title = title;
    Message = message;
    Show();
}

What you may have noticed in the Show() method is I'm calling a method called generateButtons(). As the name implies, this method is used for creating the required buttons and laying them out appropriately as required by the specified Buttons enum parameter.

private void generateButtons(Buttons buttons)
{
    switch (buttons)
    {
        case Buttons.Ok:
        {
            createOkButton();
            createOkButtonGrid();
            break;   
        }
        case Buttons.YesNo:
        {
            createYesAndNoButtons();
            createYesNoGrid();
            break;
        }
        case Buttons.OkCancel:
        {
            createOkAndCancelButtons();
            createOkCancelGrid();
            break;
        }
        case Buttons.YesNoCancel:
        {
            createYesAndNoAndCancelButtons();
            createYesNoCancelGrid();
            break;
        }
        default:
            throw new ArgumentOutOfRangeException("buttons");
    }
}

Each case statement initializes the required buttons, and creates ColumnDefinitions in a Grid for the button's layout. Below are some of the methods that are called during this process:

// Create both a [Yes] and a [No] button.
private void createYesAndNoButtons()
{
    createYesButton();
    createNoButton();
}

// Creates and initializes the [Yes] button. Also hooks up the Click event handler, 
// setting the ChildWindow's DialogResult to true, allowing the developer
// to determine the choice the user made when clicking the button.
private void createYesButton()
{
    if (_yesButton != null) return;

    _yesButton = new Button
        {
            Content = "Yes",
            Margin = new Thickness(2)
        };
        
    _yesButton.Click += (sender, args) => DialogResult = true;
}

// Sets up the Grid layout for a [Yes/No] button combination, and adds
// a [Yes] and [No] button to the Grid.
private void createYesNoGrid()
{
    resetAndClearGrid(ButtonsGrid);
    addColumnDifinitionsToGrid(ButtonsGrid, 2);
    addButtonToGrid(ButtonsGrid, _yesButton, 0);
    addButtonToGrid(ButtonsGrid, _noButton, 1);
}

// Adds a Button object to a grid at the specified Grid's column index.
private static void addButtonToGrid(Panel grid, UIElement button, int columnIndex)
{
    grid.Children.Add(button);
    button.SetValue(Grid.ColumnProperty, columnIndex);
}

And there you have it - Message Box ala ChildWindow, compliments of the Silverlight Toolkit!

One last thing to mention, the message box result (whether [Yes], [No], [OK], or [Cancel] was clicked by the user) is stored in the ChildWindow class' DialogResult property, which is a nullable bool. This can be interpreted as follows:

// Hook into the Closed event defined in the ChildWindow class, and retrieve
// the true/false value from the ChildWindow's DialogResult property.
messageBox.Closed += (s, e) => { var result = messageBox.DialogResult; };

History

  • First release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Wayne Delport
Software Developer
South Africa South Africa
No Biography provided

Comments and Discussions

 
Questioncustom message box that behaves like MessageBox? Pinmemberjoc.luz25-Oct-11 10:35 
GeneralMy vote of 3 PinmemberZorayr Khalapyan2-Feb-11 13:31 
QuestionWhy not use Simple Silverlight Message Boxes? PinmemberZorayr Khalapyan2-Feb-11 13:30 
Check out this project on CodePlex at Simple but Cool Silverlight Message Boxes. It has very easy to use Silverlight message boxes like info, error, confirm, text input, combo input, etc. and they all ship with free icons.
 
Here is some example code:
 

//Info Message.
Message.InfoMessage("Hello! I am here to help you!");
 
//Error Message.
Message.ErrorMessage("Darn! Something went wrong.");
 

 
Smile | :)
 

Live demo can be found on Microsoft Expression Community[^] site.
AnswerRe: Why not use Simple Silverlight Message Boxes? PinmemberWayne Delport4-Feb-11 1:43 
GeneralUseful! Pinmemberricas30-Nov-10 1:48 
GeneralCannot resolve TargetName DisabledVisual Pinmembervitoravelino11-Dec-09 9:02 
GeneralRe: Cannot resolve TargetName DisabledVisual PinmemberWayne Delport25-Jan-10 20:14 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 8 Oct 2009
Article Copyright 2009 by Wayne Delport
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid