-1
我正在C#中創建一個WPF項目。我有一個button
,當我點擊button
時,我想改變它的background image
。但是,首先,我想將button
的當前background image
與另一個進行比較,然後對其進行更改。這是我的代碼:將按鈕的背景圖像與WPF中的另一個圖像比較
private void homeLightsButton_Click(object sender, RoutedEventArgs e)
{
//image for Lights ON
Uri lightsOn = new Uri("images/homeLightsOn.jpg", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(lightsOn);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
//image for Lights OFF
Uri lightsOff = new Uri("images/homeLightsOff.jpg", UriKind.Relative);
StreamResourceInfo streamInfo1 = Application.GetResourceStream(lightsOff);
BitmapFrame temp1 = BitmapFrame.Create(streamInfo.Stream);
var brush1 = new ImageBrush();
brush1.ImageSource = temp1;
if (homeLightsButton.Background == brush)
{
homeLightsButton.Background = brush1;
}
else
{
homeLightsButton.Background = brush;
}
}
問題出在if
語句中;從我所瞭解的方式,我比較background image
到另一個image
是錯誤的。我已經搜索論壇,但我找不到任何東西。有任何想法嗎?
怎麼會這樣可能工作呢?您正將'homeLightsButton.Background'與新創建的ImageBrush實例進行比較。該比較總是會返回「false」。除此之外,你爲什麼以這種奇怪的方式創建一個BitmapFrame?在WPF中,通常將圖像文件的** Build Action **(在Visual Studio項目中)設置爲** Resource **,並通過[資源文件包URI](https://msdn.microsoft .com/en-us/library/aa970069(v = vs.110).aspx),像'var bitmap = new BitmapImage(new Uri(「pack:// application:,,,/images/homeLightsOn.jpg」) );' – Clemens