Posts Tagged ‘MVVM’

Many desktop applications have their own status bar embedded and docked to the bottom of the app. Recently I was working on an application where this was the case. Periodically, messages get sent to the status bar when things happen in the app (file saved, transferring data, error reported, etc). At first, these messages would remain in the status bar until a new message was received. However, I only wanted the message to be displayed for a short duration of time, say ten seconds. This is an MVVM application and my first thought was to just play a storyboard that sets the opacity of the message to zero after 10 seconds. When a new message arrives, set the opacity back to 1, then after 10 seconds fade to zero again. It sounded simple, but I was not sure of how to play the storyboard from my ViewModel in the MVVM structure.

After doing some digging around, I came to realize that I didn’t have to do anything in the ViewModel and a property I never used before came in very handy…. so I guess I’ll tell you what that property was, ­čś«, Binding.NotifyOnTargetUpdated. The MSDN says it “gets or sets a value that indicates whether to raise the TargetUpdated event when a value is transferred from the binding source to the binding target.” Now, lets say I set this property to true on a TextBlock.Text’s binding. In layman’s terms, when the text changes, the TargetUpdated event is thrown and I can use that to run my storyboard. How simple!! Here is an example.

<TextBlock Text="{Binding Path=StatusBarText, NotifyOnTargetUpdated=True}">
        <EventTrigger RoutedEvent="Binding.TargetUpdated">
                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0" To="1.0" />
                    <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:2" From="1.0" To="0.0" BeginTime="0:0:10" />

Now, when the binding updates, the opacity of the text is initially set to 1. Then, after ten seconds, the opacity will begin to fade to zero in a span of two seconds. Viola! The storyboard plays when the target text is updated and there is no need to muck up the ViewModel. Happy coding!

Read Full Post »