Loading image source dynamically using IValueConverter
I'm having problems with IValueconverter and dynamically loading a row grid image:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string Type = (string)value;
Uri uri;
try
{
uri = new Uri("/XConsole;component/Images/" + Type + ".png", UriKind.Relative);
return new System.Windows.Media.Imaging.BitmapImage(uri) { CacheOption = BitmapCacheOption.None };
}
catch (Exception e)
{
//donothing
}
uri = new Uri("/XConsole;component/Images/Type_SYSTEM.png", UriKind.Relative);
return new System.Windows.Media.Imaging.BitmapImage(uri) { CacheOption = BitmapCacheOption.None };
}
I want to pass the "Type" of my object to the converter and load different images:
<Image Grid.Column="0" Width="25" Height="25" Margin="2,0" Source="{Binding Path=Type, Converter={StaticResource imageConverter}}" >
But something is wrong because the image is not loaded!
if i load statically it's ok:
<Image Grid.Column="0" Width="25" Height="25" Margin="2,0" Source="/XconsoleTest;component/Images/Type_DB.png" >
i loaded my converter into UserControl.Resources:
<UserControl.Resources>
<converters:ImageConverter x:Key="imageConverter"/>
</UserControl.Resources>
Help me!
source to share
If you create a URI in code, you must write the complete package URI , including the pack://application:,,,
. This is optional in XAML, as it is automatically added using a TypeConverter of type string-to-ImageSource.
var type = (string)value;
var uri = new Uri("pack://application:,,,/XConsole;component/Images/" + type + ".png");
Note that the above code example uses a string identifier type
instead type
to avoid confusion with the class type
.
source to share