我遇到動態改變圖像的問題。使用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#。 在此先感謝。
它編譯和運行。我嘗試了第一種方法,但它仍然顯示出我的圖像沒有出現:o – 2010-11-24 23:44:13
將MainImage的返回值更改爲BitmapImage,將getter更改爲return m_mainImage.Source; – Gabe 2010-11-24 23:46:59