从资源中绑定显示图像-WPF

6

我是一位有用的助手,可以为您进行文本翻译。

我有一个资源图标,其关键字是:xxx

我想将它绑定到xaml中的一个图片上...

1:

  <Image Source="{x:Static p:Resources.xxx}"></Image>

2:

  <Image>
     <Image.Source>
         <BitmapImage UriSource="{Binding x:Static p:Resources.xxx}"/>
        </Image.Source>
   </Image>

3:

 <Image Source=" {Binding x:Static p:Resources.xxx,Converter={StaticResource IconToBitmap_Converter}}"></Image>

4:

 <Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding x:Static p:Resources.xxx,Converter={StaticResource IconToBitmap_Converter}}"/>
    </Image.Source>
 </Image>

以上方法不起作用,我该怎么办?

这个回答解决了你的问题吗?在WPF应用程序中从资源设置图像源 - StayOnTarget
3个回答

20

首先,您必须将图像添加到解决方案资源文件中。接下来,您必须将图像的构建操作设置为资源,然后您可以在XAML代码中像这样使用它:

<UserControl>
<UserControl.Resources>
    <ResourceDictionary>
        <BitmapImage x:Key="name" UriSource="Resources/yourimage.bmp" />
    </ResourceDictionary>
</UserControl.Resources>
<Grid>
    <Image  Source="{StaticResource name}"/>
</Grid>
</UserControl>

3

首先:添加rsx资源, 然后:将图像作为资源添加到资源文件中,并将图像生成操作设置为Resource。 现在你可以像这样访问图像:

<Image Source="pack://application:,,,/Resources/image.png"/>

0
您可以实现自己的标记扩展并按以下方式使用它:
<Image Source="{ex:ImageSource {x:Static p:Resources.xxx}}"></Image>

MarkupExtension ImageSource 可以长成这样:

public class ImageSource : MarkupExtension
{
    private readonly object source;

    public ImageSource(object source) => this.source = source;

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        Binding sourceBinding = source is Binding binding ? binding : new Binding() { Source = source };
        MultiBinding converterBinding = new MultiBinding() { Converter = new SourceConverter() };
        converterBinding.Bindings.Add(sourceBinding);

        return converterBinding.ProvideValue(serviceProvider);
    }

    private class SourceConverter : IMultiValueConverter
    {
        public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture) => BitmapToSource(value[0] as Bitmap);

        public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture) => throw new NotSupportedException();

        private BitmapImage BitmapToSource(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                memory.Position = 0;
                BitmapImage bitmapimage = new BitmapImage();
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapimage.EndInit();
                return bitmapimage;
            }
        }
    }
}

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