Search code examples
xamluwpdatagridtouchuwp-xaml

How to override the default response to a touch for a control in UWP?


Is it possible to override the response to a touch interaction for a control in UWP? For example, for a DataGrid XAML control, the default behavior when a row is tapped is to select this row and deselect all other selected rows. Can this be changed to have the tapped row added to the selection as if the control key was pressed?

EDIT: My solution is for Surface Pro in tablet mode so the user would only interact with the app via touch. So I wanted him to be able to select multiple items using touch only. In the image I added, the default behavior if the user clicks on "Chicken Sandwich" is to deselect "Burger" and select "Chicken Sandwich" unless the CTRL key is held down. However using the CTRL key on Surface device without mouse and keyboard would mean that we will need to have the on-screen keyboard on display which would be a bit cumbersome. I would like instead to change the default behavior where if the user clicks on an unselected item it's added to the selection, and if he clicks on a selected item the item it gets removed from selection (in the example below, "Chicken Sandwich" will be added to the selection on first touch and removed from selection on second tap), so basically same functionality as holding the CTRL key down but without using it.

enter image description here


Solution

  • Based on the document, the DataGrid class provides the behavior that selecting multiple items while holding down the SHIFT or CTRL keys during selection. What you need to do is just to set the SelectionMode property as Extended.

    Update:

    Please check the following code as a sample:

    List<object> selectedItems = new List<object>();
    bool flag = false;
    
    private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if(flag==false)
        {
            var item = dataGrid.SelectedItem;
            if (selectedItems.Contains(item))
            {
                selectedItems.Remove(item);
            }
            else
            {
                selectedItems.Add(item);
            }
    
            flag = true;
            dataGrid.SelectedItems.Clear();
            foreach(var cur in selectedItems)
            {
                flag = true;
                dataGrid.SelectedItems.Add(cur);
            }
        }
        else
        {
            flag = false;
        }
    }