2012-09-02 51 views
0

在我的项目中,我有一个名为Images的文件夹,其中我应用程序中使用的所有图像都保存在子文件夹中。所有图像在构建过程中都设置为“Resource”。xaml&wpf中的多路绑定图像源

myproject 
    |__Images 
     |__AppImages 
      |__StarOn.png 
      |__StarOff.png 

现在,如果我做的手动设置我的形象是这样的:

<Image Source="Images\AppImages\StarOn.png" width="32" height="32"/> 

图像中的imagebox显示正确。

我想用转换器把图像和这样的绑定:

<Image> 
<Image.Source> 
    <Binding Path="Number" converter="{StaticResource GetImagePathConverter}"/> 
</Image.Source> 
</Image> 

,其中数字是整数

,我的转换是:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     int questionNr=int.parse(value.ToString()); 

      if (questionNr>100) 
      { 
       return "Images\\AppImages\\StarOn.png"; 
      } 

      return "Images\\AppImages\\starOff.png"; 
    } 

但这是不是改变了图像?

什么iam做错了? 如何从转换器正确设置图像源?

在此先感谢

回答

4

您的使用转换器是不正确的方法。您需要创建一个转换器的实例,通过StaticResource在绑定中使用它。 local:是,你需要在你的XAML声明局部命名空间 -

<Image> 
    <Image.Resources> 
    <local:GetImagePathConverter x:Key="GetImagePathConverter"/> 
    </Image.Resources> 
    <Image.Source> 
    <Binding Path="Number" Converter="{StaticResource GetImagePathConverter}"/> 
    </Image.Source> 
</Image> 

此外,Source属性不是字符串类型,而是ImageSource所以你需要在你的转换器的东西 -

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    int questionNr=int.parse(value.ToString()); 

    if (questionNr>100) 
    { 
     return new BitmapImage(new Uri("Images\\AppImages\\StarOn.png", UriKind.Relative)); 
    } 
    return new BitmapImage(new Uri("Images\\AppImages\\StarOff.png", UriKind.Relative)); 
} 
+0

嗨...谢谢你的答案..iam在我的代码中正确使用它..我只是忘了写在这里...再次感谢我将编辑我的问题 – lebhero

+0

你的答案中的回报是不是类型ImageSource ..好吗? – lebhero

+0

BitmapImage实现了最终从ImageSource派生的类BitmapSource。因此返回类型是'ImageSource'。 –

0

this answer

基本上,您必须处理您在转换器中返回的对象类型,因此无法将string返回到ImageSource类型的属性。

我不是我的dev的机器,但代码是这样的:

return new BitmapImage(new Uri(the/path/to/image.png)).Source; //or '*.ImageSource', can't remember 
+0

谢谢。 ..正确的答案,无需设置源或图像源.. – lebhero