WPF如何实现点击Button后背景色变成红色,再次点击变回原来颜色?
WPF如何实现点击Button后背景色变成红色,再次点击变回原来颜色?
[解决办法]
Button控件有点特殊,要想改变button的背景色,你要重写button的模板的。
下面是一个示例,具体的你再自己写:
xaml代码:
<Button FontSize="16" FontWeight="Bold" x:Name="btnBackground" Background="AliceBlue">Click Me
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
bool flag = true;
void btnBackground_Click(object sender, RoutedEventArgs e)
{
if (flag)
{
this.btnBackground.Background = new SolidColorBrush(Colors.Blue);
}
else
{
this.btnBackground.Background = new SolidColorBrush(Colors.AliceBlue);
}
flag = !flag;
}