WPF:"类型的值“字符串'不能被转换为”System.Windows.Media.ImageSource'"。字符串、转换为、类型、WPF

2023-09-04 02:43:49 作者:段念尘

我想设置一个WPF图像的来源。

XAML 和

 <图像名称=ImageThing
       来源=图像/ Thing.png/>
 

Visual Basic中失败:

  ImageThing.Source =图像/ Thing.png
 

…与此的异常

  

键入字符串的值不能为   转换到   System.Windows.Media.ImageSource。

如何创建我需要的System.Windows.Media.ImageSource?

更新

WPF开源项目 WPF ControlBase

这code改编自一个 MSDN例如的作品

 昏暗BMP作为新的BitmapImage()
bmp.BeginInit()
bmp.UriSource =新的URI(图像/ Thing.png,UriKind.Relative)
bmp.EndInit()
ImageThing.Source = BMP
 

解决方案

WPF使用隐式类型转换到XAML字符串转换为预期的​​类型。在code,你是静态的对象类型绑定...如果你看的例如这里它显示了如何将源属性设置为从本地URI编程产生的BitmapImage。

I'm trying to set a WPF Image's source.

XAML works:

<Image Name="ImageThing"
       Source="images/Thing.png"/>

Visual Basic fails:

ImageThing.Source = "images/Thing.png"

…with this exception:

Value of type 'String' cannot be converted to 'System.Windows.Media.ImageSource'.

How do I create the System.Windows.Media.ImageSource that I need?

Update

This code adapted from an MSDN example works:

Dim bmp As New BitmapImage()
bmp.BeginInit()
bmp.UriSource = New Uri("images/Thing.png", UriKind.Relative)
bmp.EndInit()
ImageThing.Source = bmp

解决方案

WPF uses an implicit type converter to convert the xaml string to the expected type. In code you are statically bound by the object type... If you look at the example here it shows how to set the source property to a BitmapImage that is generated from a local uri programatically.