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

时间:2017-02-18 14:24:23

标签: c# wpf button compare background-image

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

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

1 个答案:

答案 0 :(得分: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"/>

并按照以下方式编写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"];
}