Yuval Spiegel
Yuval Spiegel

Reputation: 29

How can I switch between two methods in one button with every click?

I am new on C# so sorry if it look easy for some of you :)

I have this button click:

private void buttonSwitchCamera_Click(object sender, RoutedEventArgs e)
{
        _blManager.SendTrackerCmd(TrackerCmdType.PrimaryAVT_ActiveSensor, (float)IR_Id.IR_1); // Switch to IR1
        _blManager.SendTrackerCmd(TrackerCmdType.PrimaryAVT_ActiveSensor, (float)IR_Id.IR_2); // Switch to IR2
}

How can I switch between the two methods when clicking the button?

one click will be for method #1

second click will be for method #2

third click will be for method #1

etc..

Upvotes: 2

Views: 1520

Answers (2)

Nguyen Kien
Nguyen Kien

Reputation: 1927

First click is old:

    private void OnButtonClickOdd(object sender, RoutedEventArgs e)
    {
        // Unsubscribe OnButtonClickOdd
        button.Click -= OnButtonClickOdd;

        // Subcribe to OnButtonClickEven
        button.Click += OnButtonClickEven;

        // Do your job here
    }

    private void OnButtonClickEven(object sender, RoutedEventArgs e)
    {
        // Unsubscribe OnButtonClickEven
        button.Click -= OnButtonClickEven;

        // Subcribe to OnButtonClickOdd
        button.Click += OnButtonClickOdd;

        // Do your job here
    }

Other way: just use bool flag to know it odd or even click:

private bool odd = true;

private void buttonSwitchCamera_Click(object sender, RoutedEventArgs e)
{
    if(old)
    {
         // Odd click job
    }
    else
    {
         // Even click job
    }
    old = !old;
}

Upvotes: 1

Nikola
Nikola

Reputation: 2132

You can do something like that:

bool executeMethodOne;

private void buttonSwitchCamera_Click(object sender, RoutedEventArgs e)
{
   executeMethodOne = !executeMethodOne;

   var IrId = executeMethodOne ? IR_Id.IR_1 : IR_Id.IR_2;

    _blManager.SendTrackerCmd(TrackerCmdType.PrimaryAVT_ActiveSensor, (float)IrId);
}

Have a bool called executeMethodOne which you will invert everytime you click on the button. Depending on if it is true or false you can execute the first or the second method

Upvotes: 5

Related Questions