Loading images source dynamically with IValueConverter

本小妞迷上赌 提交于 2019-11-28 09:22:12

问题


I've problems with IValueconverter and dynamically load 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 to converter a "Type" of my object and load different images:

 <Image Grid.Column="0"  Width="25" Height="25" Margin="2,0" Source="{Binding Path=Type, Converter={StaticResource imageConverter}}" >

But there is something wrong because no picture are 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 in UserControl.Resources:

<UserControl.Resources>
    <converters:ImageConverter x:Key="imageConverter"/>
</UserControl.Resources>

Help me!!


回答1:


If you create the URI in code you have to write the full Pack URI including the pack://application:,,, part. In XAML this is not necessary as it is automatically added by the string-to-ImageSource TypeConverter.

var type = (string)value;
var uri = new Uri("pack://application:,,,/XConsole;component/Images/" + type + ".png");

Note that the above code sample uses a lowercase type identifier instead of Type to avoid confusion with the Type class.



来源:https://stackoverflow.com/questions/14858189/loading-images-source-dynamically-with-ivalueconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!