2010-10-24 68 views
25

我将几个图像配置为应用程序资源。在C#代码中更改WPF窗口背景图像

当我的应用程序启动,主窗口的背景是通过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异常。

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

回答

34

这个怎么样:

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

第二个,因为我定义了一个静态常量。谢谢! – biasedbit 2010-10-24 19:36:33

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

7

这里找到关于这更细节的XAML版本

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

我只需将一个图像中“d drive-- >数据 - > 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; 

最后我得到的背景.. enter image description here

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

我一直在尝试所有的答案,没有成功。下面是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; 

资产文件夹在我的项目的第一级去做,所以一定要改变路径为方便最简单的方法。