Thursday, November 6, 2008

Light box effect with WPF.

Light box effect is becoming a trend to show modal dialog in both web and desktop applications now a days. In WPF we can also achieve this goal with little effort. Its not actually a light box but give users a elusion of a light box.

Wpf Container controls display last element of the logical tree on top of all visual elements. we have used that feature to produce this effect. First of all we are going to add a grid as the root element of a page or window, and we are going to add the dialog XAML as the last child of the grid.


<Border x:Name="panelDialog" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<!--While Xmal Content of the dialog will go here-->
</Grid>
</Border>




Just put two function for hide and display the dialog. Total Code is given bellow. In bellow code I have Displayed a loading screen with light box effect. When displaying modal dialog just invoke show and hide wait screen methods. Its good to send your cpu expansive jobs to background thread and use dispatcher to update UI while you are in background thread.


 


XAML CODE





<Page x:Class="Home">
<Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<!--All the contents will go here-->
</ScrollViewer>
<Border x:Name="panelLoading" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<local:TMEWaitScreen></local:TMEWaitScreen>
</Grid>
</Border>
</Grid>
</Page>




C# CODE




#region About Wait Screen
/// <summary>
/// Show wait screen before a web request
/// </summary>
public void ShowWaitScreen()
{
Process del = new Process(ShowWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void ShowWaitScreenUI()
{
panelLoading.Visibility = Visibility.Visible;
}
/// <summary>
/// Hide a wait screen after a web request
/// </summary>
public void HideWaitScreen()
{
Process del = new Process(HideWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void HideWaitScreenUI()
{
panelLoading.Visibility = Visibility.Collapsed;
}
#endregion


Best of luck and happy programming.