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变量,在button的click事件中写代码改变背景色:
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;
}
[解决办法]
如果你要变回原来颜色的话,就先把原来的颜色保存一份。
public MainWindow()
{
InitializeComponent();
this.btnBackground.Click += new RoutedEventHandler(btnBackground_Click);
b = this.btnBackground.Background.Clone();
}
bool flag = true;
Brush b;
void btnBackground_Click(object sender, RoutedEventArgs e)
{
if (flag)
{
this.btnBackground.Background = new SolidColorBrush(Colors.Red);
}
else
{
this.btnBackground.Background = b;
}
flag = !flag;
}