I was looking at my site traffic and noticed that one of my most popular posts was about creating a custom MessageBox. This post was written two years ago and continues to get a lot of traffic. Since writing that post, I’ve updated my MessageBox a lot. I’ve changed it to use async/await, modified the style, corrected some bugs, and added functionality. Since I’ve made a lot of changes, and that post continues to get a lot of readers, I thought it would be good to give the latest version.
I continue to use a UserControl approach for this because I don’t want any overriding of styles. It has a set look, and should not be allowed to be changed (aside from the use of static resources). The xaml only need a small change to the bottom margin. Instead of 12 all around, it needed 18 on the bottom. I also changed the name of the first Grid from MessagePanel to LayoutRoot, this wasn’t needed, but made some code behind easier to understand what element was being modified.
<Grid x:Class="Pinnacle.Controls.MessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Margin="0">
<Grid.Background>
<SolidColorBrush Color="{StaticResource PhoneBackgroundColor}" Opacity=".5"/>
</Grid.Background>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}"
VerticalAlignment="Top" HorizontalAlignment="Stretch"
toolkit:TiltEffect.IsTiltEnabled="True" >
<StackPanel x:Name="MessagePanel" Margin="12">
<TextBlock x:Name="HeaderTextBlock" TextWrapping="Wrap"
Style="{StaticResource PhoneTextLargeStyle}"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"
HorizontalAlignment="Left"/>
<TextBlock x:Name="MessageTextBlock" TextWrapping="Wrap"
Style="{StaticResource PhoneTextNormalStyle}"
FontSize="{StaticResource PhoneFontSizeMedium}"
Margin="12,24,12,24"
HorizontalAlignment="Left"/>
<Grid HorizontalAlignment="Stretch" Margin="0,6,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="YesButton" Click="YesButton_Click"/>
<Button x:Name="NoButton" Grid.Column="1" Click="NoButton_Click"/>
</Grid>
</StackPanel>
</Grid>
</Grid>
The code behind saw a lot of changes as can be seen in this diff comparison from WinMerge.
The first change was to make the Show method awaitable. This requires removing the Closed event, and the use of a TaskCompletionSource. We need to wait awhile for user interaction, so we’ll create a member wide TaskCompletionSource. Bold is for new code.
private readonly TaskCompletionSource<MessageBoxResult> _completeionSource;
private MessageBox()
{
InitializeComponent();
_completeionSource = new TaskCompletionSource<MessageBoxResult>();
}
public static Task<MessageBoxResult> ShowAsync(string message, string caption, string yesButtonText, string noButtonText = null)
{
MessageBox msgBox = new MessageBox();
msgBox.HeaderTextBlock.Text = caption;
msgBox.MessageTextBlock.Text = message;
msgBox.YesButton.Content = yesButtonText;
if (string.IsNullOrWhiteSpace(noButtonText))
{
msgBox.NoButton.Visibility = Visibility.Collapsed;
}
else
{
msgBox.NoButton.Content = noButtonText;
}
msgBox.Insert();
return msgBox._completeionSource.Task;
}
The previous MessageBox fired the Closed event and then removed the MessageBox from the active page. When changing to using the TaskCompletionSource, I changed to set the result after the MessageBox was removed from the page. Within the Completed event handler of the transition, set the result.
_completeionSource.SetResult(result);
I intentionally left out most of the code of the remove method because I wanted to save the best for last. The last bit that I added is something no other custom MessageBox does. We need to account for apps that have changed the SystemTray of the page.
The MessageBox needs to change the BackgroundColor of the SystemTray to be the PhoneChromeBrush color. If the user changes the Opacity of the SystemTray to be less than 1 the MessageBox needs to account for it. If the Opacity is less than one, then the page will be shifted up into the tray. This has always bugged me about the Opacity property of the SystemTray and the ApplicationBar. Rather than just changing the opacity (whether you can see behind it), it also changes the page layout by shifting the page content up. If you show any other custom MessageBox in this state, you will see the background of the page in the SystemTray rather than seeing the PhoneChromeBrush resource color. To account for this, We need to detect if the tray has an opacity. If it does, add a large margin to the top.
private void Insert()
{
// Make an assumption that this is within a phone application that is developed "normally"
var frame = Application.Current.RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame;
_page = frame.Content as PhoneApplicationPage;
// store the original color, and change the tray to the chrome brush
_originalTrayColor = SystemTray.BackgroundColor;
SystemTray.BackgroundColor = ((SolidColorBrush)Application.Current.Resources["PhoneChromeBrush"]).Color;
bool shouldBuffer = SystemTray.Opacity < 1;
if (shouldBuffer)
{
// adjust the margin to account for the page shifting up
Margin = new Thickness(0, -32, 0, 0);
var margin = MessagePanel.Margin;
MessagePanel.Margin = new Thickness(margin.Left, 64, margin.Right, margin.Bottom);
}
_page.BackKeyPress += Page_BackKeyPress;
// assume the child is a Grid, span all of the rows
var grid = System.Windows.Media.VisualTreeHelper.GetChild(_page, 0) as Grid;
if (grid.RowDefinitions.Count > 0)
{
Grid.SetRowSpan(this, grid.RowDefinitions.Count);
}
grid.Children.Add(this);
// Create a transition like the regular MessageBox
SwivelTransition transitionIn = new SwivelTransition();
transitionIn.Mode = SwivelTransitionMode.BackwardIn;
ITransition transition = transitionIn.GetTransition(LayoutRoot);
EventHandler transitionCompletedHandler = null;
transitionCompletedHandler = (s, e) =>
{
transition.Completed -= transitionCompletedHandler;
transition.Stop();
};
transition.Completed += transitionCompletedHandler;
transition.Begin();
if (_page.ApplicationBar != null)
{
// Hide the app bar so they cannot open more message boxes
_page.ApplicationBar.IsVisible = false;
}
}
When the MessageBox is removed, we then need to set the BackgroundColor back to it’s original value.
private void Remove(MessageBoxResult result)
{
_page.BackKeyPress -= Page_BackKeyPress;
var frame = (PhoneApplicationFrame)Application.Current.RootVisual;
var page = frame.Content as PhoneApplicationPage;
var grid = VisualTreeHelper.GetChild(page, 0) as Grid;
// Create a transition like the regular MessageBox
SwivelTransition transitionOut = new SwivelTransition();
transitionOut.Mode = SwivelTransitionMode.BackwardOut;
ITransition transition = transitionOut.GetTransition(LayoutRoot);
EventHandler transitionCompletedHandler = null;
transitionCompletedHandler = (s, e) =>
{
transition.Completed -= transitionCompletedHandler;
SystemTray.BackgroundColor = _originalTrayColor;
transition.Stop();
grid.Children.Remove(this);
if (page.ApplicationBar != null)
{
page.ApplicationBar.IsVisible = true;
}
_completeionSource.SetResult(result);
};
transition.Completed += transitionCompletedHandler;
transition.Begin();
}
In both methods, I also corrected a memory leak with the event handlers. Always remember to unsubscribe from those inline events! As always, here is a zip of the source.