-3

I have a user control with two buttons (Add, Delete). When accessed from the main window, how do I know which button were being clicked?

btnAdd had a method while btnDelete has another method that should be invoked.

Servy
  • 202,030
  • 26
  • 332
  • 449

2 Answers2

0

Create two separate Command for button add and delete in MainWindow

And you can bind your command in userControl like this:

<Button Command={Binding AddCommand}/>

and set the datacontext of Mainwindow to itself inside XAML or in a constructer

this.datacontext = this;

For more information on how to create Command see this and this

tabby
  • 1,878
  • 1
  • 21
  • 39
-1

If I understand your issue correctly, you could cast the sender argument in the event handler:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button button = sender as Button;
    if (button.Name == "btnAdd ")
    {
        //add button was clicked...
    }
    else if (button.Name == "btnDelete")
    {

    }
}

<Button x:Name="btnAdd" Content="Add" Click="Button_Click" />
<Button x:Name="btnDelete" Content="Delete" Click="Button_Click" />
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    It makes no sense to assign the same handler to two different buttons if you just want to do completely different things when either is clicked. – Servy Sep 08 '17 at 15:58
  • You may not want to do *completely* different things. It is hard to say what the OP wants. But casting the sender argument is a way to "know which button were being clicked". – mm8 Sep 08 '17 at 16:01
  • The two *different handlers* can both call some of the same methods (or the same methods with different arguments) if their behavior is similar. The point remains that if you want to do different things when different buttons are clicked you should give them different handlers, not give them the same handler, then check the button, so you can then go do two different things. – Servy Sep 08 '17 at 17:26