WPF - 如何将背景颜色设置为图像按钮

时间:2017-07-13 11:27:28

标签: c# wpf background-image background-color

我有一个带有背景图像的按钮,我想在点击它时为这个按钮添加背景颜色 这就是我将图像背景设置为按钮的方式:

XAML:

<Button x:Name="ScannerButton" DockPanel.Dock="Right" Visibility="Collapsed" Click="ScannerButton_Click" Margin="0,0,5,25" Height="70" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75">
    <Button.Template>
        <ControlTemplate>
            <Image Source="/Resources/scanner.png"></Image>
        </ControlTemplate>
    </Button.Template>
</Button>

This is how I want it to look like when I click on it

1 个答案:

答案 0 :(得分:2)

例如,您可以将其设为ToggleButton,并在IsChecked属性设置为true时添加更改背景的触发器:

<ToggleButton x:Name="ScannerButton" DockPanel.Dock="Right" Visibility="Collapsed" Click="ScannerButton_Click" Margin="0,0,5,25" Height="70" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75">
    <ToggleButton.Template>
        <ControlTemplate TargetType="ToggleButton">
            <Grid x:Name="grid">
                <Image Source="/Resources/scanner.png"></Image>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter TargetName="grid" Property="Background" Value="Green" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ToggleButton.Template>
</ToggleButton>