Search content within the blog

Monday, December 5, 2011

DataTriggers in WPF

This post shows how you can implement data triggers in WPF.

The code is self explanatory. The window consists of textboxes which turn red in foreground color if a value of a memeber of a itemsource to which the data is bounded is set to false.

The data is bound using XML data provider.

Put the follo0wing ina XML file.

<members>
<member>
<isactive>true</isactive>
<groupcolor>#FFCC3333</groupcolor>
<name>Tom Jackson</name>
</member>
<member>
<isactive>false</isactive>
<groupcolor>#FFA4AB28</groupcolor>
<name>Stacey Footheart</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FFA6D877</groupcolor>
<name>Jack Herdin</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FF138C48</groupcolor>
<name>Kim Getruds</name>
</member>
<member>
<isactive>false</isactive>
<groupcolor>#FF5FADB9</groupcolor>
<name>Larry Nusom</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FF3B1076</groupcolor>
<name>Gary Heart</name>
</member>
</members>

Place the folowing in a XAML file.

<Window x:Class="datatriggers_cs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="datatriggers_cs" Height="300" Width="300"
>
<Window.Resources>
<XmlDataProvider Source="members.xml" x:Key="memberslist" />

<Style x:Key="itemstyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="Green" />
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=isactive}" Value="false">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>

</Window.Resources>

<Grid>
<ItemsControl ItemsSource="{Binding Source={StaticResource memberslist}, XPath=/members/member}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderBrush="SlateBlue" BorderThickness="2" Background="White" CornerRadius="3">
<TextBlock Style="{StaticResource itemstyle}" Text="{Binding XPath=name}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>


OUTPUT
----------


No comments:

Post a Comment