日期:2014-05-17  浏览次数:21822 次

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);