I am having issues of having an image change dynamically.
Some background info:
I have a list box that contains elements that can be selected. These items are food categories.
When a user clicks on one of the foods, I would like an image at a different location of the page to change.
My Xaml file contains:
<Image Name="bigImage" Stretch="Fill" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
So when the user clicks a certain food category that “bigImage” would change:
FoodCollection foods = (FoodCollection)this.FindResource("FoodCategory");
Food f = foods[foodListBox.SelectedIndex];
Title_TextBlock.Text = f.Name;
bigImage = f.MainImage;
In my food class I have a variable called Image 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));
}
}
}
I read somewhere that I had to “resolve” the image, but I was unclear on what that meant.
I thought this would do it:
m_mainImage.BeginInit();
m_mainImage.Source = new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute));
m_mainImage.EndInit();
Sorry I am still new to WPF and C#.
Thanks in advance.
Have you set the
DataContextof the window?Without this
PropertyChangedwon’t be initialised, so:will never fire as
PropertyChangedis alwaysnull.