Click here to Skip to main content
15,881,248 members
Articles / Desktop Programming / WPF
Tip/Trick

Popup MessageBox Using Silverlight4.0

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
29 Mar 2012CPOL 13.2K   1   1
Simple but presentable message boxes for Silverlight developers. Designed for ease of integration with existing projects.

Features

  • Easy to get started and extend.
  • Message types include  Error, Confirm only. But others can include.
  • Icons are provided.

XAML:

XML
//Child Window  CustomMessage
<controls:ChildWindow x:Class="MyMessageBox.CustomMessage" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" 
      Width="293" Height="134" Title="CustomMessage">
   <Border x:Name="MessageBorder" BorderThickness="1" BorderBrush="#FF0B6CDE">
        <Grid x:Name="LayoutRoot" Margin="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="75*" />
                <ColumnDefinition Width="198*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="67*" />
                <RowDefinition Height="28*" />
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal" Grid.Row="1" 
                      VerticalAlignment="Bottom" Grid.ColumnSpan="2" Height="28" 
                      Name="ButtonStack" HorizontalAlignment="Right" Margin="0, 0, 0, 5">
                <Button x:Name="OKButton" Click="OKButton_Click" Content="OK" 
                     Width="75" Height="23" HorizontalAlignment="Center" 
                     VerticalAlignment="Bottom" Margin="0,0,6,0" 
                     VerticalContentAlignment="Center" Padding="0" />
                <Button Content="No" Height="23" x:Name="CancelButton" 
                  Click="CancelButton_Click" Width="75"  HorizontalAlignment="Center" 
                  VerticalAlignment="Bottom" Padding="3" Visibility="Collapsed" />

            </StackPanel>
            <Image Name="MessageIcon" Stretch="Uniform" VerticalAlignment="Center" 
               HorizontalAlignment="Right" Margin="0,8,6,27" Height="62" Width="56" 
               Grid.RowSpan="2" Source="/MyMessageBox;component/icon/Bullet-question-256.png" />
            <Border BorderBrush="{x:Null}" BorderThickness="1" Grid.ColumnSpan="2" 
                     Margin="67,0,0,0" Name="TextBlockBorder">
                <TextBlock TextWrapping="Wrap" Name="TextBlock" 
                   VerticalAlignment="Center" TextAlignment="Left" 
                   Text="Message" Padding="15,0,0,0" />
            </Border>
            <TextBox Grid.Column="1" Height="21" HorizontalAlignment="Left" 
               Margin="9,42,0,0" Name="InputTextBox" VerticalAlignment="Top" 
               Width="182" Visibility="Collapsed" FontSize="10" Padding="0.5" />
            <ComboBox Grid.Column="1" Height="21" HorizontalAlignment="Left" 
               Margin="9,42,0,0" Name="InputComboBox" VerticalAlignment="Top" 
               Width="182" Visibility="Collapsed" FontSize="10" Padding="5,0,0,0"/>
        </Grid>
    </Border>
</controls:ChildWindow>

C# code for child window:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;

namespace MyMessageBox
{
    public partial class CustomMessage : ChildWindow
    {       
        public enum MessageType { Info, Error, Confirm, TextInput, ComboInput };        
        public string Input { get; set; }      
        private const string ICONS_PATH = "/SilverlightMessageBoxes;component/icons/";
        public CustomMessage(string message, MessageType type = 
                     MessageType.Info, String[] inputOptions = null)
        {
            InitializeComponent();

            switch (type)
            {

                case MessageType.Info:                  
                    break;

                case MessageType.TextInput:
                case MessageType.ComboInput:
                   
                    this.TextBlock.VerticalAlignment = VerticalAlignment.Top;
                    
                    Thickness newBorderMargin = this.TextBlockBorder.Margin;
                    newBorderMargin.Top += 5;
                    this.TextBlockBorder.Margin = newBorderMargin;
                  
                    if (type == MessageType.ComboInput)
                    {
                        this.InputComboBox.ItemsSource = inputOptions;

                      
                        /**
                        if (inputOptions != null && inputOptions.Length != 0)
                            this.InputComboBox.SelectedIndex = 0;
                        */

                        this.InputComboBox.Visibility = Visibility.Visible;
                    }
                    else //TextBox input.
                    {
                        this.InputTextBox.Visibility = Visibility.Visible;
                    }
                    break;

                case MessageType.Error:
                    setMessageIcon("button_cancel-256.png");
                    this.MessageBorder.BorderBrush = new SolidColorBrush(Colors.Red);
                    break;
                case MessageType.Confirm:
                    setMessageIcon("Bullet-question-256.png");
                    this.MessageBorder.BorderBrush = new SolidColorBrush(Colors.Orange);
                    this.OKButton.Content = "Yes";
                    this.CancelButton.Content = "No";
                    this.CancelButton.Visibility = Visibility.Visible;

                    break;
            }

            //Set the message.
            this.TextBlock.Text = message;
        }
       
        private void setMessageIcon(string imagePath)
        {
            MessageIcon.Source = new BitmapImage(
              new Uri(ICONS_PATH + imagePath, UriKind.RelativeOrAbsolute));
        }

        #region Button Hanlders

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

            //Check to see if the input text box was visiable
            //and that at least some text was entered.
            if (this.InputTextBox.Visibility == Visibility.Visible
                && this.InputTextBox.Text.Length > 0)

                //Store the text in the textbox input into Input property.
                Input = InputTextBox.Text;

            //Else check to see if the input combo box was visible.
            else if (this.InputComboBox.Visibility == Visibility.Visible
                    && this.InputComboBox.SelectedItem != null)

                //Store the selected value.
                Input = (String)InputComboBox.SelectedValue;

            //If no input was received, set the Input property to null
            //so users can check if the input was empty.
            else
                Input = null;

            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        #endregion

        #region Keyboad Event Handlers

        private void keyDown(object sender, KeyEventArgs e)
        {
            //Click the OK button if enter was pressed on the textbox.
            if (e.Key == Key.Enter)
            {
                // Create a ButtonAutomationPeer using the ClickButton.
                ButtonAutomationPeer buttonAutoPeer = new ButtonAutomationPeer(OKButton);

                // Create an InvokeProvider.
                IInvokeProvider invokeProvider = 
                  buttonAutoPeer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;

                // Invoke the default event, which is click for the button.
                invokeProvider.Invoke();
            }
        }

        #endregion
    }
}

// Message Class

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MyMessageBox
{
    public static class Message
    {

        /// <summary>
        /// Outputs a user-friendly error message.
        /// </summary>
        /// <param name="message">The message to display.</param>
        public static void ErrorMessage(string message)
        {
            new CustomMessage(message, CustomMessage.MessageType.Error).Show();
        }

        /// <summary>
        /// Outputs a user-friendly info message.
        /// </summary>
        /// <param name="message">The message to display.</param>
        public static void InfoMessage(string message)
        {
            new CustomMessage(message, CustomMessage.MessageType.Info).Show();
        }


    }
}
////From front End Button

private void btnCall_Click(object sender, RoutedEventArgs e)
{  
    CustomMessage customMessage = new CustomMessage("Do you like me?",  
                  CustomMessage.MessageType.Confirm);

    customMessage.OKButton.Click += (obj, args) =>
    {
        Message.InfoMessage("Thanks. You make me blush.");
    };

    customMessage.CancelButton.Click += (obj, args) =>
    {
        Message.ErrorMessage("Wrong answer! Your computer will distruct in 10 seconds...");
    };

    customMessage.Show();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    CustomMessage customMessage = new CustomMessage("Its Error!!!!!!?", 
                  CustomMessage.MessageType.Error);

    customMessage.OKButton.Click += (obj, args) =>
    {
        Message.InfoMessage("You Choos error");
    };
               customMessage.Show();
}

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionScreenshot? Pin
Kevin Marois29-Mar-12 9:08
professionalKevin Marois29-Mar-12 9:08 

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.