A.Manikandan
A.Manikandan

Reputation: 19

Two seperate click event in single button using wpf

Button Control Template

<ControlTemplate x:Key="status">
        <StackPanel Orientation="Horizontal" Width="60" Height="60"  Background="#8eb548">
            <Button Content="Ad" Width="20" Height="40" Margin="7 0 0 0" Click="btn1_click"/>
            <Button Content="Ch" Width="20" Height="40" Margin="5 0 0 0" Click="btn2_click"/>
        </StackPanel>
</ControlTemplate>

Button

<Button Template="{StaticResource status}" Width="60" Height="60"/> 

I want two different button click event in single button. thats why i used two buttons for my button control template. Is that right way to do it? or is there any other way?

Upvotes: 0

Views: 1947

Answers (2)

AnjumSKhan
AnjumSKhan

Reputation: 9827

There are numerous ways of doing this :

  1. Btn.Click += Btn_Click;

    Btn.Click += Btn_Click_1;

  2. Handle Click event of both inner and outer Buttons.

     <Button x:Name="Btn" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
        <Button Content="Button" />
     </Button>
    
  3. Handle Button.Click at container level along with Button level.

    <Grid ButtonBase.Click="Grid_Click_1">
         <Button x:Name="Btn" Content="Press" Click="Btn_Click_2"/>
    </Grid>
    

Upvotes: 1

ViVi
ViVi

Reputation: 4474

Have a single button and bind it to a command. Change the command parameter as per your wish. Maybe you want 1 functionality to happen when the button content is Ch and another functionality to occur when the button content is Ad. So pass the button as command parameter. You can even pass the button content as command parameter.

<Button Content="{Binding BtnContent}" Width="20" Height="40" Margin="5 0 0 0" Command={Binding BtnClick} CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}" />

For xaml : You could just check the button content and run the 2 functionalities. For eg :

if(btn1.Content == "Ch")
{
    //Do functionality for Ch
}
else if(btn1.Content == "Ad")
{
    //Do functionality for Ad
}

Upvotes: 0

Related Questions