使用IValueConverter动态加载图像源

3

我在使用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>

帮助我!!


你在VS输出窗口中看到任何绑定错误吗? 此外,不要将“Type”用作变量名称,无论是在转换器中还是在你要绑定的对象中,因为它已经存在作为一个类。虽然我不知道这是否会导致问题。 - siger
如果我在转换器中进行调试,它会正确加载值并找到我的图像资源的URI,但是在用户界面中什么也没有显示! - davymartu
1个回答

4
如果您在代码中创建URI,则必须编写完整的Pack URI,包括pack://application:,,,部分。在XAML中,这是不必要的,因为字符串到ImageSource类型转换器会自动添加它。
var type = (string)value;
var uri = new Uri("pack://application:,,,/XConsole;component/Images/" + type + ".png");

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

我已经尝试了Uri和new BitmapImage(Uri),它们不会抛出FileNotFoundException,但在UI中总是没有任何反应... - davymartu
我找到了链接,并进行了修改:uri = new Uri(@"pack://application:,,/Images/Type_DB.png");,现在它可以正常工作了……但我不明白为什么! - davymartu
1
MSDN上关于WPF中打包URI的文章解释了一切。如果图像资源在本地程序集中(与转换器相同),则必须省略/XConsole;component部分。 - Clemens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接