2017-02-18 77 views
-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是錯誤的。我已經搜索論壇,但我找不到任何東西。有任何想法嗎?

+0

怎麼會這樣可能工作呢?您正將'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

回答

1

你可以簡單地存儲兩個ImageBrushes爲XAML資源

<Window.Resources> 
    <ImageBrush x:Key="homeLightsOn" ImageSource="images/homeLightsOn.jpg"/> 
    <ImageBrush x:Key="homeLightsOff" ImageSource="images/homeLightsOff.jpg"/> 
</Window.Resources> 

... 
<Button Background="{StaticResource homeLightsOff}" 
     Click="homeLightsButton_Click"/> 

,寫你的點擊這樣的處理程序:

private void homeLightsButton_Click(object sender, RoutedEventArgs e) 
{ 
    var button = (Button)sender; 
    button.Background = button.Background == Resources["homeLightsOff"] 
     ? (ImageBrush)Resources["homeLightsOn"] 
     : (ImageBrush)Resources["homeLightsOff"]; 
} 
+0

非常感謝!有效!! –