2012-04-08 40 views
0

在我的WP7應用程序中,所有頁面都使用ImageBrush作爲我在ResourceDictionay中定義的背景。這個ResourceDictionary是通過App.xaml全局合併的。在ResourceDictionary中的圖像刷的定義是這樣的:在運行時從ResourceDictionary更新ImageBrush

<ImageBrush x:Key="PhonePageBackground" ImageSource="/Background1.jpg"/> 

我試着在運行時更新圖像刷的ImageSource的,但它不工作。

製作一些測試,在那裏我有上有一個按鈕,一個頁面來改變的背景下,我意識到,下面的代碼工作正常:

ImageBrush image; 

    public MainPage() 
    { 
     InitializeComponent(); 

     image = new ImageBrush { ImageSource = new BitmapImage(new Uri("/Background1.jpg", UriKind.Relative)) }; 

     LayoutRoot.Background = image; 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     image.ImageSource = new BitmapImage(new Uri("/Background2.jpg", UriKind.Relative)); 
    } 

但下面的代碼,在這裏我用的是圖像刷從字典,不起作用。頁面的背景變得透明,好像圖像無法找到:

ImageBrush image; 

    public MainPage() 
    { 
     InitializeComponent(); 

     image = (ImageBrush)Application.Current.Resources["PhonePageBackground"]; 

     LayoutRoot.Background = image; 
    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     image.ImageSource = new BitmapImage(new Uri("/Background2.jpg", UriKind.Relative)); 
    } 

這兩個圖像(Background1.jpg和Background2.jpg)構建操作都設置爲內容。我已經測試過資源集,但沒有成功。

爲什麼會出現這種行爲的任何知識?

回答

1

這適用於我。

ImageBrush image; 
     public MainPage()     
     { 
      InitializeComponent(); 

      image = (ImageBrush)Application.Current.Resources["PhonePageBackground"]; 
      LayoutRoot.Background = image; 
     } 


private void button1_Click(object sender, RoutedEventArgs e) 
     { 

      image = new ImageBrush { ImageSource = new BitmapImage(new Uri("/Background2.jpg", UriKind.Relative)) }; 
      LayoutRoot.Background = image; 
    } 
+0

這確實有效,但它不是我想要完成的。您正在更新LayoutRoot.Background,但不是資源字典中的ImageBrush。我想要更新背景和ImageBrush資源。該問題已在我的另一篇文章[here]中得到解決(http://forums.create.msdn.com/forums/t/102679.aspx) – dferrazm 2012-04-09 13:44:00