Changing an Image dynamically in C# using WPF
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();
S开发者_StackOverfloworry I am still new to WPF and C#. Thanks in advance.
Have you set the DataContext
of the window?
Without this PropertyChanged
won't be initialised, so:
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
will never fire as PropertyChanged
is always null
.
Setup some TwoWay Binding:
Try:
bigImage.SetBinding(Image.SourceProperty, new Binding(){
Source = f,
Path = new PropertyPath("MainImage"),
Mode=BindingMode.TwoWay
});
Or:
<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));
}
}
Not sure if this will help, but shouldn't the call to m_mainImage.EndInit()
in the setter for MainImagePath
occur after the call for RaisePropertyChanged("MainImage")
...
Andrew
精彩评论