#1,140 – Using a Value Converter in a Template
August 20, 2014 4 Comments
You can use a value converter anywhere in XAML where you are using data binding.
Below is an example of using a value converter within a data template. The Visibility property is bound to the underlying Actor object that is the data context for the item template. The value converter then derives a value for Visibility from several properties within the Actor object. (Assume that we have an ActorList property that is a collection of Actor instances).
The XAML includes:
<Window.Resources> <loc:DeadFredConverter x:Key="deadFredConverter"/> </Window.Resources> <StackPanel> <ListBox Margin="15" Width="270" Height="320" ItemsSource="{Binding ActorList}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Source="{Binding Image}" Height="80"/> <StackPanel Margin="5"> <TextBlock Text="{Binding FullName}" FontSize="12" FontWeight="Bold"/> <TextBlock Text="{Binding Dates}"/> <TextBlock Text="{Binding KnownFor}" Margin="0,5,0,0" FontStyle="Italic"/> </StackPanel> <Label Content="Dead Fred !" Foreground="Red" FontWeight="Bold" Visibility="{Binding Converter={StaticResource deadFredConverter}}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel>
The body of the value converter is:
class DeadFredConverter : IValueConverter { // Convert to Visibility, deriving from properties on Actor object public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Actor a = (Actor)value; Visibility vis = Visibility.Hidden; if ((a.FirstName == "Fred") && a.DeathYear.HasValue && (a.DeathYear <= DateTime.Today.Year)) vis = Visibility.Visible; return vis; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }