【问题标题】:multibind image source in xaml & wpfxaml 和 wpf 中的多绑定图像源
【发布时间】:2012-09-03 02:57:46
【问题描述】:

在我的项目中,我有一个名为 Images 的文件夹,我在我的应用程序中使用的所有图像都保存在子文件夹中。所有图像在构建过程中都设置为“资源”。

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

现在,如果我像这样手动设置图像:

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

图像在图像框中正确显示。

我想使用转换器和这样的绑定来设置图像:

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

但这并没有改变图像?..

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

提前致谢

【问题讨论】:

    标签: wpf xaml binding


    【解决方案1】:

    您使用转换器的方式不正确。您需要创建一个转换器实例,通过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));
    }
    

    【讨论】:

    • 嗨...谢谢您的回答..我在我的代码中正确使用它..我只是忘了在这里写...再次感谢我会编辑我的问题
    • 您的答案中的返回不是 ImageSource ..right 类型的吗?
    • BitmapImage 实现了最终派生自 ImageSource 的类 BitmapSource。因此返回类型为ImageSource
    • 好的,我试过了,我得到一个异常:无效的URI:无法确定URI的格式。
    • 将 URI 的模式设置为 Relative。原因参考这个链接-stackoverflow.com/questions/9734120/…
    【解决方案2】:

    this answer

    基本上,您必须注意在转换器中返回的对象类型,不能将 string 返回到 ImageSource 类型的属性。

    我不在我的开发机器上,但代码是这样的:

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

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2013-01-11
      • 2017-10-09
      • 2011-03-26
      • 1970-01-01
      相关资源
      最近更新 更多