运行时出现 XamlParseException。从 x:Static 切换到相对组件字符串来引用图像可以修复此问题。为什么?

CRE*_*REW 3 c# wpf xaml image embedded-resource

我正在使用 WPF/C# 设计我的第一个主要应用程序,并且我正在尝试更好地理解引用资源。

许多指南告诉我使用我未能使用的第一种方式。

  • 我在illustrator中设计了一个资源
  • 将其设置为 96 dpi,
  • 将其另存为 png,

然后我:

  • 打开资源.resx
  • 点击添加资源->图片
  • 选择我现有的名为“SuperInt_Alert”的 PNG
  • 将该新 png 的构建类型更改为 Resource

然后,当我尝试在 xaml 中显示图像时,我使用以下命令:

xmlns:prop="clr-namespace:Stark.Properties"
Run Code Online (Sandbox Code Playgroud)

<...代码...>

<Image Source="{x:Static prop:Resources.SuperInt_Alert}"  HorizontalAlignment="Center" VerticalAlignment="Top"
               Grid.Row="1"
               Grid.Column="1"
               ></Image>
Run Code Online (Sandbox Code Playgroud)

给我一个 System.Windows.Markup.XamlParseException ,其中 Message='为'System.Windows.Markup.StaticExtension'提供值引发了异常。'。Xaml 设计器也不显示我的图像。它是空白的,但没有错误。

尽管

<Image Source="/Stark;component/Resources/SuperInt_Alert.png"  HorizontalAlignment="Center" VerticalAlignment="Top"
       Grid.Row="1"
       Grid.Column="1"
       ></Image>
Run Code Online (Sandbox Code Playgroud)

效果很好。它甚至在我的设计师中也有所体现。

为什么?

我只是想了解两种使用资源的方式之间的差异。第一种方式有什么问题。我实际上更喜欢第一种方式,因为当我输入资源名称时,它可以让我使用 IntelliSense 自动完成我的资源名称。第二种方式则不然,因为它就像一个字符串。

另外,我不必将资源类型设置为公共,对吗?我可以将其保留为内部文件,因为没有其他项目正在使用我的资源文件?我只需确保构建类型设置为资源/内容/嵌入资源,对吗?

非常感谢!

mr1*_*100 5

是的,我当然同意这个选项:Source="{x:Static prop:Resources.SuperInt_Alert}" 更好。是的,您可以而且应该使用它。而且您正确地提到了问题的原因。为了能够从 XAML 引用资源中的属性,您必须将它们公开 - 使它们在内部生成 XamlParseException,您已经提到过。我不是 100% 确定为什么会这样,但我认为这是因为 Xaml 需要解析。它由外部程序集解析。要从这些程序集中获取正确的值代码,需要引用项目中的资源,但它们是内部的,因此通常无法在程序集外部访问。

此外,您还需要将从资源加载的 Bitmap 对象转换为 ImageSource。为此,您可以使用 Binding 并应用适当的转换器。这是示例转换器类:

public class BitmapToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        MemoryStream ms = new MemoryStream();
        ((System.Drawing.Bitmap)value).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        ms.Seek(0, SeekOrigin.Begin);
        image.StreamSource = ms;
        image.EndInit();

        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的类取自http://www.shujaat.net/2010/08/wpf-images-from-project-resource.html您需要将 BitmapToImageSourceConverter 添加到窗口中的资源中:

<Window.Resources>
    <my:BitmapToImageSourceConverter x:Key="imageSourceConverter"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

以下是您应该如何定义图像以使用转换器:

 <Image Source="{Binding Source={x:Static prop:Resources.Picture1}, Converter={StaticResource imageSourceConverter}}"/>
Run Code Online (Sandbox Code Playgroud)