I have a simple template for a combobox structured in this way:
<ComboBox DockPanel.Dock="Left" MinWidth="100" MaxHeight="24"
ItemsSource="{Binding Actions}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Width="100" />
<Image Source="{Binding Converter={StaticResource TypeConverter}}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
So, if I use this code, everything works:
<TextBlock Text="{Binding Name}" Width="100" />
<!--<Image Source="{Binding Converter={StaticResource TypeConverter}}" /> -->
<Image Source="{StaticResource SecurityImage}" />
But if I use the converter it doesn't work anymore. This is the converter, but I don't know how I can refer to the static resource from there ...
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var type = (Action)value;
var img = new BitmapImage();
switch (type.ActionType)
{
case ActionType.Security:
img.UriSource = new Uri("StructureImage", UriKind.Relative);
break;
case ActionType.Structural:
img.UriSource = new Uri("SecurityImage", UriKind.Relative);
break;
}
return img;
}
Try to use the Switch Converter written by Josh, should work for you:
SwitchConverter –
No need to write your converter, your code will look like this -
Update1:
Here is code of SwitchConverter as Josh's site seems to be down -
Update2:
Another SwitchConverter implementation from Microsoft Reference Source.
When using
Image.UriSource
you need to specify the relative file path to your images if the images have been added to your project and their "Build Action" has been set to "Resource". E.g. if you have put your images in a project folder in Visual Studio called "images", you can refer to the images in the following way:If the images are not build as a resource, you have to use the full file path i.e.
EDIT:
If you put your images in your Application resourcedictionary, you can always access it in the following way:
If you put the resources somewhere else you may use a
IMultiValueConverter
instead ofIValueConverter
for your converter. Then your typeconverter would look something like the following:and your XAML would look similar to this:
Finally, this would be how you'd define your resources:
The above code is untested!