Windows Phone: Custom Message Box
In this aticle I will discuss how we can create custom message box in Windows Phone 7 (SDK).

Step 1: Create a silverlight for Windows Phone project
Step 2: Add Windows Phone User Control.
Step 3: Add below code in the .xaml of User Control. I have defined the StackPanel background color with PhoneAccentBrush.
<StackPanel Width="480" Height="226" Margin="0,0,0,0" Background="{StaticResource PhoneAccentBrush}" >
<TextBlock Text="Custom Message Box" Margin="22,110,0,0" Style="{StaticResource PhoneTextTitle3Style}"/>
<Button x:Name="MessageBoxClose" Content="close" Margin="12,0,0,0" Width="180" HorizontalAlignment="Left" />
</StackPanel>
Step 4: Add a button inside ContentPanel of MainPage.xaml.
<Button Content="Custom Message Box" HorizontalAlignment="Left" Name="customMessagebox" VerticalAlignment="Top" Click="btncustomMessagebox_Click" />
Step 5: Add System.Windows.Controls.Primitives and directive in MainPage.xaml.cs.
using System.Windows.Controls.Primitives; using System.ComponentModel;
Step 6: Declare below class level variables.
public partial class MainPage : PhoneApplicationPage
{
Popup customMessageBox = new Popup();
Canvas canvas = null;Step 7: Add below button handler which will show custom message box. I have used canvas to make the message box modal.
private void btncustomMessagebox_Click(object sender, RoutedEventArgs e)
{
canvas = new Canvas();
Color backgroundColor = (Color)Application.Current.Resources["PhoneAccentColor"];
canvas.Background = new SolidColorBrush(backgroundColor);
canvas.Margin = new Thickness(-50, 0, 0, 0);
canvas.Width = 1000;
canvas.Opacity = 0.5;
ContentPanel.Children.Add(canvas);
if (customMessageBox.Child == null)
{
CustomMessageBox messageBox = new CustomMessageBox();
messageBox.MessageBoxClose.Click += new RoutedEventHandler(CustomMessageBoxClose_Click);
customMessageBox.Child = messageBox;
}
customMessageBox.IsOpen = true;
}
Step 8: The hardware back key button needs to be handle to hide message box on press of back key.
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (customMessageBox != null && customMessageBox.IsOpen)
{
customMessageBox.IsOpen = false;
e.Cancel = true;
ContentPanel.Children.Remove(canvas);
}
}
Step 9: Below method will close the message box on click of button on message box.
private void CustomMessageBoxClose_Click(object sender, RoutedEventArgs e)
{
if (customMessageBox != null)
{
customMessageBox.IsOpen = false;
ContentPanel.Children.Remove(canvas);
}
}Step 10: Now run the application and click on Custom Message Box button. You will get the message box of accent color like shown below.
|
|
|
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)






