2010-10-24 92 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; 

資產文件夾在我的項目的第一級去做,所以一定要改變路徑爲方便最簡單的方法。