从资源字典中设置图像源

时间:2014-05-22 06:41:23

标签: c# wpf mvvm

我有一个wpf应用程序,我有一个tabcontrol,我从外部资源字典设置它的ItemTemplate,在该模板中我有一个Image Control,它绑定到我的ViewModel中的字符串Property'ImagePath'并使用转换器我将'ImagePath'转换为新的bitmapImage。我在外部资源disctinary中创建了我的转换器类实例。我在App.xaml中合并了外部字典

这是我的外部资源词典:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:helpers="clr-namespace:RH_Maize.Helper">

<helpers:ImageSourceConverter x:Key="ImageSourceConverter" />

<DataTemplate x:Key="ClosableTabItemTemplate">
    <StackPanel Width="155"
    Orientation="Horizontal"
    Height="35">
        <Image Height="25"
            Width="30"
            Source="{Binding Path=ImagePath,Converter={ StaticResource ImageSourceConverter}}"/>
        <TextBlock TextWrapping="Wrap" Text="{Binding DisplayName}"
            Width="100" Height="27" VerticalAlignment="Bottom" FontSize="15" Margin="3,0,0,0"/>
        <Button Command="{Binding CloseCommand}"
            Content="x" />
    </StackPanel>
</DataTemplate>

这是我的Converter类:

 public class ImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType == typeof(ImageSource))
        {
            if (value is string)
            {
                string str = (string)value;
                return new BitmapImage(new Uri(str, UriKind.RelativeOrAbsolute));
            }
            else if (value is Uri)
            {
                Uri uri = (Uri)value;
                return new BitmapImage(uri);
            }
        }
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我的ViewModel属性是:

  private string _ImagePath;
    public string ImagePath
    {
        get
        {
            return _ImagePath;
        }
        set
        {
            _ImagePath = value;
            RaisePropertyChanged(() => ImagePath);
        }
    }

我的问题是转换器类转换方法根本没有调用。我的代码出错了什么?

0 个答案:

没有答案