Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show a button is clicked(pressed) in WPF?

Tags:

c#

wpf

On mouse is up button should show the background border

I have created a simple style

<UserControl.Resources>
        <Style TargetType="Button" x:Key="TransparentButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Background="Transparent">
                            <ContentPresenter/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

and in button

<Button  Height="20" Width="20"  Padding="0,0,0,0" DockPanel.Dock="Top" Grid.Row="0" Grid.Column="1" Click="button_click"  Style="{StaticResource TransparentButton}"
                    BorderBrush="Transparent" BorderThickness="0" Background="Transparent">
            <Button.Content>
                <Image Source="../Resources/Help_icon.png" Stretch="UniformToFill" />
            </Button.Content>
            </Button>

But in this case when button is pressed it doesn't show up in UI. User should feel that button is pressed.

Thanks and regards

like image 331
User123 Avatar asked May 31 '12 19:05

User123


2 Answers

I'm not sure what you want visually, but if you want the border to change color when the button is pressed down, you would modify your template like this:

<Style TargetType="Button" x:Key="TransparentButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Name="border" Background="Transparent" BorderThickness="1" BorderBrush="Black">
                    <ContentPresenter/>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="Button.IsPressed" Value="True">
                        <Setter TargetName="border" Property="BorderBrush" Value="Transparent" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
like image 172
Trevor Elliott Avatar answered Oct 19 '22 23:10

Trevor Elliott


There's a good article here that explains what's going on and how to fix it. Basically MS did include this feature in the standard button, but the colors they picked for 'mouse down' and 'pressed' are so close that you don't notice the difference.

Right-click on the button in the designer, and pick "Edit Template / Edit a Copy..." and then change the colors until you can see a difference. Simple!

like image 27
Robin Bennett Avatar answered Oct 19 '22 23:10

Robin Bennett