找不到类型imageconverter

时间:2012-05-21 16:53:09

标签: wpf xaml

我正在尝试为我的图像源绑定应用转换器。这是我的xaml:

<Window.Resources>
        <DataTemplate x:Key="listBoxTemplate">
            <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <ImageConverter x:Key="MyImageConverter" />
                </StackPanel.Resources>
                <Image Source="{Binding Path=thumb, StringFormat=/WpfTest;component/Images/{0}, Converter={StaticResource MyImageConverter}}" Height="100" Width="130" Margin="5"></Image>
                <StackPanel Orientation="Vertical" Width="247">
                    <TextBlock Text="{Binding recipeName}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
                    <TextBlock Text="{Binding cuisine}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

这是我的imageConverter类:

using System;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Imaging;

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string path = (string)value;

        try
        {
            //ABSOLUTE
            if (path.Length > 0 && path[0] == System.IO.Path.DirectorySeparatorChar
                || path.Length > 1 && path[1] == System.IO.Path.VolumeSeparatorChar)
                return new BitmapImage(new Uri(path));

            //RELATIVE
            return new BitmapImage(new Uri(System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + path));
        }
        catch (Exception)
        {
            return new BitmapImage();
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是当我尝试运行应用程序时,它返回“未找到类型图像转换器”并且VS突出显示该部分

<ImageConverter x:Key="MyImageConverter" />

在上面的xaml中。我如何解决它? (顺便说一下,我从Wpf - relative image source path获得了imageconverter代码)

1 个答案:

答案 0 :(得分:2)

您需要添加如下命名空间:

<ns:ImageConverter x:Key="MyImageConverter"/>

并确保您将命名空间添加到更高的位置:

<DataTemplate xmlns:ns="....">

实际的命名空间取决于您的项目,但代码完成将对您有所帮助。