Saturday, August 22, 2009

WPF auto fading error message

Here is a small control template to display an error message. The message will fade away after a couple of seconds. You set the message like this:-

Label1.Content = DateTime.Now.ToString();

Here is the xaml:-

<Windowx:Class="TRM_Uploader.Window2"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Window2"Height="300"Width="300"><Window.Resources><ControlTemplatex:Key="MyErrorMessage"TargetType="{x:Type Label}"><StackPanelOrientation="Horizontal"Name="ErrorMessage"><BorderCornerRadius="4"BorderThickness="0"Background="Red"VerticalAlignment="Center"Margin="4,0"BorderBrush="Transparent"><LabelForeground="White"VerticalAlignment="Center"Padding="4,2"FontWeight="Bold"Name="Part1"Visibility="Visible">Error</Label></Border><!-- This TextBlock accepts the content from the parent 'label'. It is not actually displayed, just used to bind data--><TextBlockName="Part3"Text="{TemplateBinding Content}"Visibility="Collapsed"></TextBlock><!-- This TextBlock binds to the one above and triggers an animation when it gets updated. --><!-- Its required because TemplateBinding does not allow NotifyOnTargetUpdate --><TextBlockMargin="2"Name="Part2"Foreground="Red"Padding="3"Text="{Binding ElementName=Part3, Path=Text,NotifyOnTargetUpdated=True}"VerticalAlignment="Center"></TextBlock></StackPanel><ControlTemplate.Triggers><!-- When Text property of Part2 is blank hide entire control--><TriggerSourceName="Part3"Property="Text"Value=""><SetterTargetName="ErrorMessage"Property="Visibility"Value="Hidden"></Setter></Trigger><!-- This trigger is called when Part2 updates which in turn is updated by Part3's databind. It uses animation to make the label fade away after a few seconds. --><EventTriggerSourceName="Part2"RoutedEvent="Binding.TargetUpdated"><BeginStoryboard><StoryboardTargetName="ErrorMessage"><DoubleAnimationStoryboard.TargetProperty="Opacity"Duration="0:0:0"To="1.0"/><DoubleAnimationStoryboard.TargetProperty="Opacity"Duration="0:0:2"From="1.0"To="0.0"BeginTime="0:0:1"/></Storyboard></BeginStoryboard></EventTrigger></ControlTemplate.Triggers></ControlTemplate></Window.Resources><StackPanelOrientation="Vertical"><LabelTemplate="{StaticResource MyErrorMessage}"Name="Label1"></Label><ButtonClick="button1_Click">click to test</Button></StackPanel></Window>