[英]Changing an Image dynamically in C# using WPF
我遇到了動態更改圖像的問題。
一些背景信息:我有一個列表框,其中包含可以選擇的元素。 這些項目是食品類別。 當用戶點擊其中一種食物時,我希望頁面其他位置的圖像發生變化。
我的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#的新手。 提前致謝。
設置一些雙向綁定:
嘗試:
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));
}
}
您是否設置了窗口的DataContext
?
沒有此PropertyChanged
將不會初始化,因此:
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
永遠不會觸發,因為PropertyChanged
始終為null
。
不知道這是否會幫助,但不應該調用m_mainImage.EndInit()
的setter方法MainImagePath
呼吁后發生RaisePropertyChanged("MainImage")
...
安德魯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.