在C#代码中更改WPF窗口背景图片

30

我有几张被配置为应用程序资源的图片。

当我的应用程序启动时,主窗口的背景通过XAML设置:

<Window.Background>
    <ImageBrush ImageSource="/myapp;component/Images/icon.png" />
</Window.Background>

如果发生某个事件,我想将这个背景更改为另一个资源("/myapp;component/Images/icon_gray.png")。

我尝试使用两个常量:

private static readonly ImageBrush ENABLED_BACKGROUND =
    new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon.png")));
private static readonly ImageBrush DISABLED_BACKGROUND =
    new ImageBrush(new BitmapImage(new Uri("/myapp;component/Images/icon_gray.png")));

...但是自然会得到一个无效URI的异常。

是否有一种简单的方法可以使用打包URI或资源(即Myapp.Properties.Resources.icon)来更改WPF窗口的背景图像(通过this.Background = ...)?

7个回答

42

这个怎么样:

new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "Images/icon.png")))
或者,这样做:
this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")));

使用第二个,因为我正在定义一个静态常量。谢谢! - biasedbit

10

这里是 XAML 版本

<Window.Background>
    <ImageBrush>
        <ImageBrush.ImageSource>
            <BitmapImage UriSource="//your source .."/>
        </ImageBrush.ImageSource>
    </ImageBrush>
</Window.Background>

6
问题出在您在代码中使用它的方式。请尝试以下代码。
public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

您可以在http://msdn.microsoft.com/en-us/library/aa970069.aspx上找到更多关于此的详细信息。


0
Uri resourceUri = new Uri(@"/cCleaner;component/Images/cleanerblack.png", UriKind.Relative);
            StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
            BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
            var brush = new ImageBrush();
            brush.ImageSource = temp;
            frame8.Background = brush;

0

我只是把一张图片放在"D盘-->Data-->IMG"文件夹中。这张图片的名称是x.jpg

在C#代码中输入:

ImageBrush myBrush = new ImageBrush();

myBrush.ImageSource = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), "D:\\Data\\IMG\\x.jpg"));

(请在路径之间放置双斜杠)

this.Background = myBrush;

终于我得到了背景... 在此输入图片描述


0

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);


0

我已经尝试了所有这里的答案,但都没有成功。以下是使用ms-appx最简单的方法。

        ImageBrush myBrush = new ImageBrush();
        Image image = new Image();
        image.Source = new BitmapImage(new Uri(@"ms-appx:///Assets/background.jpg"));
        myBrush.ImageSource = image.Source;
        TheGrid.Background = myBrush;

Assets文件夹位于我的项目的第一层,所以请确保根据需要更改路径。


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