I have a few images defined in my resource section of my UI :
<Window.Resources>
<!-- Converters -->
<loc:UserStatusToIconConverter x:Key="UserStatusToIconConverter" />
<!-- Images -->
<BitmapImage x:Key="ConnectIcon" UriSource="/WPFClient;component/Images/connect.png" />
<BitmapImage x:Key="ActiveIcon" UriSource="/WPFClient;component/Images/active.png" />
<BitmapImage x:Key="IdleIcon" UriSource="/WPFClient;component/Images/idle.png" />
<BitmapImage x:Key="AwayIcon" UriSource="/WPFClient;component/Images/away.png" />
<BitmapImage x:Key="UnknownIcon" UriSource="/WPFClient;component/Images/unknown.png" />
...
I would like to select one of these for a binding in my converter, I assume this would be more efficient than creating a new image each time (500 times) from the converter.
public class UserStatusToIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string userStatus = value.ToString();
string iconName = ...;
switch (userStatus)
{
case "Active":
// select ActiveIcon;
break;
case "Idle":
// select IdleIcon;
break;
case "Away":
...
break;
}
return iconName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Here is where I use it :
<ListBox ItemsSource="{Binding Users}">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<Image Source="{Binding Status, Converter={StaticResource UserStatusToIconConverter}}" Height="16" Width="16" />
<TextBlock Text="{Binding Nick}" />
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I think you're better off using DataTemplate.Triggers
in this case rather than a Converter:
<DataTemplate>
<DockPanel>
<Image x:Name="Img" Height="16" Width="16" />
<TextBlock Text="{Binding Nick}" />
</DockPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="Active">
<Setter TargetName="Img" Property="Source" Value="{StaticResource ActiveIcon}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="Idle">
<Setter TargetName="Img" Property="Source" Value="{StaticResource IdleIcon}"/>
</DataTrigger>
<!-- And So on... -->
</DataTemplate.Triggers>
</DataTemplate>