2010-11-24 44 views
2

我遇到動態改變圖像的問題。使用WPF在C#中動態更改圖像

一些背景信息: 我有一個列表框,其中包含可以選擇的元素。這些項目是食品類別。 當用戶點擊其中一種食物時,我想要改變頁面不同位置的圖像。

我的XAML文件包含:

<Image Name="bigImage" Stretch="Fill" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center"/> 

因此,當用戶點擊某一種食物的類別,「bigImage」將發生變化:

FoodCollection foods = (FoodCollection)this.FindResource("FoodCategory"); 
      Food f = foods[foodListBox.SelectedIndex]; 
      Title_TextBlock.Text = f.Name; 
      bigImage = f.MainImage; 

在我的食品類我有一個變量稱爲圖像m_mainImage :

public class Food 
    { 
     ... 

     Image m_mainImage = new Image(); 
     String m_mainImagePath = string.Empty; 

     ... 

     public string MainImagePath{ 
      get { return m_mainImagePath; } 
      set 
      { 
       m_mainImagePath = value; 
       m_mainImage.BeginInit(); 
       m_mainImage.Source = new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
       m_mainImage.EndInit(); 
       RaisePropertyChanged("MainImage"); 
       RaisePropertyChanged("MainImagePath"); 
      } 
     } 

     public Image MainImage 
     { 
      get { return m_mainImage; } 
     } 


     public event PropertyChangedEventHandler PropertyChanged; 
     protected void RaisePropertyChanged(string name) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(name)); 
     } 

    } 
} 

我在某處讀到我必須「解析」圖像,但我是uncl瞭解這意味着什麼。 我認爲這將做到這一點:

m_mainImage.BeginInit(); 
        m_mainImage.Source = new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
        m_mainImage.EndInit(); 

對不起,我還是新的WPF和C#。 在此先感謝。

回答

0

您是否設置窗口的DataContext

沒有這個PropertyChanged不會被初始化,所以:

if (PropertyChanged != null) 
    PropertyChanged(this, new PropertyChangedEventArgs(name)); 

將永遠不會觸發爲PropertyChanged總是null

0

設置一些雙向綁定:

嘗試:

bigImage.SetBinding(Image.SourceProperty, new Binding(){ 
     Source = f, 
     Path = new PropertyPath("MainImage"), 
     Mode=BindingMode.TwoWay 
    }); 

或者:

<Image Name="bigImage" 
     Stretch="Fill" 
     Grid.Row="0" 
     Grid.Column="0" 
     HorizontalAlignment="Center" 
     VerticalAlignment="Center" 
     Source="{Binding Path=MyBitmapImage, Mode=TwoWay}"/> 

public BitmapImage MyBitmapImage 
{ 
    get 
    { 
     return new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
    } 
} 
+0

它編譯和運行。我嘗試了第一種方法,但它仍然顯示出我的圖像沒有出現:o – 2010-11-24 23:44:13

+0

將MainImage的返回值更改爲BitmapImage,將getter更改爲return m_mainImage.Source; – Gabe 2010-11-24 23:46:59

0

不知道這是否會幫助,但呼籲RaisePropertyChanged("MainImage")後不應該在setter方法MainImagePath調用m_mainImage.EndInit()發生......

安德魯