-1

如何在 image1 的 c# 中更改图像源,WPF?

<Image 
            Visibility="Visible"
           Name="image1"
            Source="/Panorama-Kocka;component/slike/kocka.PNG"
            Grid.Column="1"
            Grid.Row="0" 
            Stretch="Fill"
            />
4

1 回答 1

1

在遇到与您相同的问题并阅读后,我发现了解决方案 - Pack URIs。

我在代码中做了以下事情:

Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage()
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/ApplicationName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;

URI 分为几部分:

Authority: application:///

Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path
    AssemblyShortName: the short name for the referenced assembly.
    ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
    ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
    ;component: specifies that the assembly being referred to is referenced from the local assembly.
    /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.

应用后的三个斜杠:必须用逗号替换:

Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details.

当然,请确保将图像上的构建操作设置为 Resource。

于 2012-09-01T11:33:09.893 回答