Home > View Post

DataTriggers. Does WPF have an answer for everything

Let's take our example data from yesterday's post about databinding being more than just dynamic updating and beef it up a little.

    <XmlDataProvider x:Key="data">
            <Data xmlns="">
                <Value Currency="GBP">20</Value>
                <Value Currency="GBP">100</Value>
                <Value Currency="GBP">70</Value>
                <Value Currency="USD">130</Value>
                <Value Currency="GBP">40</Value>

We've added a currency attribute (wow). Now let's imagine that we want our chart to fill the bars Navy for GBP but Green for USD. There's no obvious way of achieving this given the linear nature of the ItemsControl. Step forward DataTriggers.


It's as easy as this:

<Rectangle Name="rect" Height="{Binding XPath=.}" Width="50" Fill="Navy" Stroke="Black" VerticalAlignment="Bottom" />
    <DataTrigger Binding="{Binding XPath=@Currency}" Value="USD">
        <Setter TargetName="rect" Property="Fill" Value="Green"/>

Coloured Bar Chart

Note how we specify the Name property of the rectangle "rect" in the Setter's TargetName property. Too easy.

Tags: WPF

Josh Post By Josh Twist
11:12 AM
22 Mar 2007

» Next Post: theJoyOfCode Team Reunite
« Previous Post: More than just dynamic updating

Comments are closed for this post.

Posted by Richard @ 02 Sep 2010 8:33 PM
Hi Josh,

I am struggling with data triggers - I have a class that creates and send messages to a queue, and I have rectangle controls that do glow one by one with about 2 seconds intervals - how can I send a message to the queue everytime the rectangle change colours?
my code snippet looks like this:
...the rectangle that is animated
<Rectangle Canvas.Left="262" Canvas.Top="98" Width="36" Height="23" Name="pl1" Visibility="Visible" Fill="Black" RadiusX="1" RadiusY="1" RenderTransformOrigin="10,0" />

...the animation when a button is clicked
<!--The color, the duration, and the targeted property that will Be subject of the aniamtion, all parameters are set within the animation tag -->
<ColorAnimation Storyboard.TargetName="pl1"
Duration="00:00:08" AutoReverse="False"
From="Black" To="Orange"
<ColorAnimation Storyboard.TargetName="pl1"
Duration="00:00:08" AutoReverse="False"
From="Orange" To="Black"
<ColorAnimation Storyboard.TargetName="light2"
Duration="00:00:02" AutoReverse="False"
From="#FFF75F06" To="#3EB80C"

could you help please?

Posted by Josh @ 03 Sep 2010 6:28 PM
Hi Richard, Thanks for the comment but I can't provide adhoc consultancy to questions like this on the blog. Have you tried www.stackoverflow.com? You'll get an answer there very quickly there I expect! Good luck!

PS - One clue for you though - look into the ViewModel (MVVM) patter to see how you can separate logic like this out of your view (XAML).

© 2005 - 2022 Josh Twist - All Rights Reserved.