使用WPF在C#中动态更改图像

问题描述:

我遇到动态改变图像的问题。使用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#。 在此先感谢。

您是否设置窗口的DataContext

没有这个PropertyChanged不会被初始化,所以:

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

将永远不会触发为PropertyChanged总是null

设置一些双向绑定:

尝试:

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

不知道这是否会帮助,但呼吁RaisePropertyChanged("MainImage")后不应该在setter方法MainImagePath调用m_mainImage.EndInit()发生......

安德鲁