用C#代码更改WPF窗口背景图像

我有几个图像配置为应用程序资源。

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

   

如果发生给定事件,我想将此背景更改为另一个资源( "/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 = ... )?

那这个呢:

 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"))); 

这里是XAML版本

        

问题是你在代码中使用它的方式。 试试下面的代码吧

 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

我只是在“d drive – > 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; 

最后我得到了背景.. 在此处输入图像描述

 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; 

我一直在尝试所有的答案,没有成功。 这是使用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文件夹位于我项目的第一级,因此请确保方便地更改路径。