0

I have an array of visual elements on a page, any of which can be long-pressed. In code, I can get a command to run when a button is long-pressed:

for (int i = 0; i < choiceButtons.Length; i++)
{
    TouchEffect.SetLongPressCommand(choiceButtons[i], new Command( async () =>
    {
        // Do stuff here, depending which button was long-pressed
    }));
    TouchEffect.SetLongPressCommandParameter(choiceButtons[i], choiceButtons[i].Text);
}

However, I need to be able to determine which visual element is the one that was long-pressed. Is there a way to do that?

(The visual elements are subclassed from Grid.)

[EDIT: Indexes corrected]

BillF
  • 1,034
  • 3
  • 13
  • 28
  • use the CommandParameter – Jason Sep 08 '21 at 13:12
  • @Jason the CommandParameter takes a visual element as its first parameter, but which visual element is the thing we don't know - chicken and egg? – BillF Sep 08 '21 at 14:46
  • pass the VisualElement as the 2nd parameter too – Jason Sep 08 '21 at 14:50
  • @Jason Thanks - will check into that. – BillF Sep 08 '21 at 14:51
  • Replace `choiceButtons[i].Text` with `choiceButtons[i]`. – ColeX Sep 09 '21 at 08:13
  • @ColeX As suggested, I replaced choiceButtons[i].Text with choiceButtons[i] in the last line. Afraid I still can't work out what code to put in the Command lambda, to determine which button was long-pressed. For example, TouchEffect.GetLongPressCommandParameter(choiceButtons [j]); returns a valid non-null button for every j, not just for the long-pressed button. – BillF Sep 09 '21 at 12:17
  • I found a solution; will post it as answer below. – BillF Sep 09 '21 at 13:42
  • You can mark your solution if problem has been solved. – ColeX Sep 10 '21 at 01:14

1 Answers1

0

Here is the solution I found. Thanks to Jason and ColeX.

for (int i=0; i < choiceButtons.Length; i++)
{
    TouchEffect.SetLongPressCommand(choiceButtons[i], new Command(async () =>
    {
        // Here when a button is long-pressed
        object obj;
        for (int j=0; j < choiceButtons.Length; j++)
        {
            if (TouchEffect.GetState(choiceButtons [j] ) != TouchState.Pressed)
                continue;
            obj = TouchEffect.GetLongPressCommandParameter(choiceButtons[j]);
            if (obj != null)
            {
                MyButton btn = (MyButton)obj;  // This is the button that was long-pressed
                await HandleLongPressAsync (btn);   // Do stuff
                break;
            } 
    }));
    TouchEffect.SetLongPressCommandParameter(choiceButtons[i], choiceButtons[i]);
}

BillF
  • 1,034
  • 3
  • 13
  • 28