Martina Stefanoska
Martina Stefanoska

Reputation: 85

Implement Click Event on a WPF control inside WPF

This is connected with my previous question as it's dealt with the same piece of code; now that I've accomplished the changing of the background of the button, the problem is that now i need to implement the same code but not not for ButtonPressed but for clicked button. I've added click handlers in the code but it's not working - the background is not changing. I tried different approaches, even with using bitmaps and imagesources, but it's not working, the change simply does not happen. Now I want to implement the change of the background image but it needs to be done in the XAML file, not in the .cs . Again the code:

<Button x:Class="proba4.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="120" d:DesignWidth="300" IsEnabled="True">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Grid>
                <Image Name="Normal" Source="C:\stuff\off_button.gif"/>
                <Image Name="Pressed" Source="C:\stuff\on_button.gif" Visibility="Hidden"/>

            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
                    <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
                </Trigger>

            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>

Note that I've already looked for some button properties for clicking, but there was none, and all the implementations I've found on internet are dealing with adding Button_Click method in the .cs code of the control, and since that is not working for me, I need to find another way - hopefully something like fully implemented click control using WPF. I guess this is delicate, but I will greatly appreciate any help with this, thanks.

Upvotes: 0

Views: 550

Answers (1)

John Bowen
John Bowen

Reputation: 24453

It sounds like you want the behavior of a ToggleButton, not a Button. On Button clicking is a discrete event rather than a state that the control goes into that can be expressed by a property. A ToggleButton switches back and forth between two (or three) states when clicked, and the IsChecked property represents the state and can be bound in a Trigger like you're doing with IsPressed in your example.

Upvotes: 1

Related Questions