2017-02-18 89 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

非常感谢!有效!! –