在WPF中指定图像源的正确方法是什么?

时间:2018-05-29 08:49:06

标签: c# wpf

我想在WPF中使用窗口的背景图像。我打算使用ImageBrush。我将图像放在根文件夹中,也放在Assets文件夹中。

我在StackOverflow中找到了很多答案来提供URI,但似乎都失败了。

public MainWindow()
{
    InitializeComponent();
    Content = new MainPage();

    Image image = new Image
    {
        //Source = new BitmapImage(new Uri("/MyWPFApp;component/myimage.jpg"))           // Invalid URI: The format of the URI could not be determined.
        //Source = new BitmapImage(new Uri("/MyWPFApp;component/Assets/myimage.jpg"))    // Invalid URI: The format of the URI could not be determined.
        //Source = new BitmapImage(new Uri("/MyWPFApp;/Assets/myimage.jpg"))             // Invalid URI: The format of the URI could not be determined.

        //Source = new BitmapImage(new Uri(@"\myimage.jpg", UriKind.Relative))                      // Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).
        //Source = new BitmapImage(new Uri(@"\Assets\myimage.jpg", UriKind.Relative))               // Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

        //Source = new BitmapImage(new Uri("pack://MyWPFApp:,,,/myimage.jpg"))           // The URI prefix is not recognized

    };
    MyBrush.ImageSource = image.Source;
}

什么是正确的格式?何时应使用上述格式?

P.S:这些正在运作

    <ImageBrush x:Name="MyBrush" Opacity="0.3" ImageSource="/Assets/myimage.jpg"  Stretch="UniformToFill"/>
    <ImageBrush x:Name="MyBrush" Opacity="0.3" ImageSource="/myimage.jpg"  Stretch="UniformToFill"/>

1 个答案:

答案 0 :(得分:1)

如果要从

后面的代码中分配图像,则需要使用包网址
Image image; // ...
image.Source = new BitmapImage(new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));

你可以对这个网址应该做些什么的独立研究,但很可能会对你的情况类似:

pack://application:,,,/MyWPFApp;component/Assets/myimage.jpg