xamarin.formsxamarin-community-toolkit

Determine which visual element was long-pressed in TouchEffect? - Xamarin Community Toolkit


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]


Solution

  • 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]);
    }