我遇到动态更改图像的问题。
一些背景信息: 我有一个列表框,其中包含可以选择的元素。这些项目是食品类别。 当用户点击其中一种食物时,我希望页面不同位置的图像发生变化。
我的 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;
在我的食物类中,我有一个名为 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));
}
}
}
我在某处读到我必须“解析”图像,但我不清楚那是什么意思。 我认为这会做到这一点:
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
。
关于c# - 使用 WPF 在 C# 中动态更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271067/