I am having some problems with WPF, and I was wondering if anyone knew what I should try next. So essentially I have a processing window, that is bound to a list of strings and each gets an Image in a Listbox.
The Code I have for it so far is as follows.
<ListBox x:Name="MyListBox" ItemsSource="{Binding Items}" Margin="36,100,320,100" SelectedIndex="0" Panel.ZIndex="1" MouseDoubleClick="MyListBox_MouseDoubleClick">
<ListBox.Resources>
<BitmapImage x:Key="checkmark" UriSource="Images/checkmark.gif" />
<BitmapImage x:Key="failure" UriSource="Images/red-x.gif" />
<BitmapImage x:Key="processing" UriSource="Images/processing.gif" />
<BitmapImage x:Key="white" UriSource="Images/white.gif" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{DynamicResource white}" />
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I have tried following multiple online articles but I can't seem to be able to change my resource from white to any of the other keys. So I think my next step is to point the dynamic resource to a class that determines the status of each object, but I can't seem to get it to update the images whatsoever.
I have tried
MyListBox.SelectedItem = MyListBox.FindResource("checkmark");
MyListBox.InvalidateArrange();
MyListBox.UpdateLayout();
and a bunch of others but it didn't seem to do much. I am new to WPF, so I apologize for the newbie question but any help or nudges in the right direction would be extremely helpful. Thanks in advance.
You can use a DataTrigger
or Trigger
on the DataTemplate
to change the image source. If you use a DataTrigger
then you'll need another property to hold the name of the image you want to show, along with the text to be bound. For example:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<BitmapImage x:Key="checkmark" UriSource="Images/checkmark.gif" />
<BitmapImage x:Key="failure" UriSource="Images/red-x.gif" />
<BitmapImage x:Key="processing" UriSource="Images/processing.gif" />
<BitmapImage x:Key="white" UriSource="Images/white.gif" />
</StackPanel.Resources>
<Image x:Name="image" Source="{StaticResource white}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
<DataTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Source" TargetName="image" Value="{StaticResource checkmark}"/>
</Trigger>
<DataTrigger Binding="{Binding ImageToShow}" Value="failure">
<Setter Property="Source" TargetName="image" Value="{StaticResource failure}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
For more info, take a look at the MSDN doc.