Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

c# - WPF changing button background on click

I have a set of buttons in a side panel. I want to change the background of the button that has been clicked. I have tried to do that using style.trigger and the only property I could think of is IsPressed, but that doesn't help that much since it changes the background for a second (till the button is pressed [duh]).

This is the code I've tried:

<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
    <Setter Property="Background" Value="SlateGray" />
    <Setter Property="Foreground" Value="White"></Setter>
</Trigger>
</Style.Triggers>

Another way I could think of was creating individual style for each button with a datatrigger since I've a property that changes with the selection of the button, but that seems like a overkill. Any idea how can I highlight a button that has been clicked?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This kind of trigger runs when your condition is fulfilled and then the effect disappears. In order to set for good instead of a while take a look at this

<Button Content="Content" Background="Red">
        <Button.Triggers>
            <EventTrigger RoutedEvent="MouseEnter">
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="CadetBlue"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Button.Triggers>
    </Button>

Since IsPressed is not a RoutedEvent you can use this

 <Button Content="Content" Background="Red">
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <Trigger Property="IsPressed" Value="True">
                        <Trigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="CadetBlue"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </Trigger.EnterActions>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...