我在WPF的网格中有一个按钮,只需单击该按钮,背景就会被新图像替换。我的代码如下:
<Button Grid.Row="0" Grid.Column="0" Content="1" FontSize="100" Foreground="White" >
<Button.Background>
<ImageBrush ImageSource="{Binding MyImgSource}" />
</Button.Background>
</Button>
但我的问题是,我希望在用户按下按钮之前按钮的背景为黑色,因此在用户点击之前不会有任何图像吸收。所以我想知道无论如何我可以告诉按钮背景为黑色而不提供黑色图像作为图像源?
答案 0 :(得分:1)
据我了解,您想在用户按下按钮后一次更改背景?如果是这样,您可以使用带动画的样式:
<Window x:Class="ButtonBackground.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Black"/>
<Setter Property="FontSize" Value="100"/>
<Setter Property="Foreground" Value="White"/>
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Button.Background)" >
<ObjectAnimationUsingKeyFrames.KeyFrames>
<DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="Black"/>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame.Value>
<!--<SolidColorBrush Color="Pink"/>-->
<ImageBrush ImageSource="{Binding MyImgSource}" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames.KeyFrames>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" Content="1" Style="{StaticResource ButtonStyle}" />
</Grid>
</Window>
如果您想在按下后将黑色背景返回按钮,那么您的风格将是:
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Black"/>
<Setter Property="FontSize" Value="100"/>
<Setter Property="Foreground" Value="White"/>
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background">
<Setter.Value>
<!--<SolidColorBrush Color="Pink"/>-->
<ImageBrush ImageSource="{Binding MyImgSource}" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>