使用IValueConverter动态加载图像源 [英] Loading images source dynamically with IValueConverter

查看:87
本文介绍了使用IValueConverter动态加载图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用IValueconverter时遇到问题,并动态加载了行网格图像:

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" >

我在UserControl.Resources中加载了我的转换器:

i loaded my converter in UserControl.Resources:

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

救救我!!

推荐答案

如果在代码中创建URI,则必须编写完整的

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");


请注意,上面的代码示例使用小写的type标识符而不是Type,以避免与Type类混淆.


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

这篇关于使用IValueConverter动态加载图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆