使用IValueConverter动态加载图像源

时间:2013-02-13 16:28:00

标签: c# wpf ivalueconverter imagesource imultivalueconverter

我遇到IValueconverter问题并动态加载行网格图像:

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 };

}

我想将转换器传递给我的对象的“类型”并加载不同的图像:

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

但是有一些错误,因为没有加载图片!

如果我静态加载,没关系:

 <Image Grid.Column="0"  Width="25" Height="25" Margin="2,0" Source="/XconsoleTest;component/Images/Type_DB.png" >

我将我的转换器加载到UserControl.Resources:

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

救救我!!

1 个答案:

答案 0 :(得分:4)

如果您在代码中创建URI,则必须编写完整的Pack URI,包括pack://application:,,,部分。在XAML中,这不是必需的,因为它是由字符串到ImageSource TypeConverter自动添加的。

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

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

相关问题