将按钮的背景图像与 WPF 中的另一个图像进行比较



我正在用C#创建一个WPF项目。我有一个button,单击button时我想更改其background image。但是,首先,我想将button的当前background image与另一个进行比较,然后进行更改。这是我的代码:

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进行比较的方式是错误的。我已经搜索了论坛,但我找不到任何东西。有什么想法吗?

你可以简单地将两个图像画笔存储为 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"/>

并像这样编写您的 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"];
}

相关内容

  • 没有找到相关文章

最新更新