Holding event for desktop app not firing

2019-08-06 08:22发布

问题:

In my Universal Windows App, I am subscribing to the Holding event in my ListViewItem DataTemplate:

        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Holding="ListViewItem_Holding">
                    <FlyoutBase.AttachedFlyout>
                        <MenuFlyout Placement="Right">
                            <!-- using the Click event -->
                            <MenuFlyoutItem Text="delete" Click="DeleteProductClick" />

                            <MenuFlyoutItem Text="edit" />
                        </MenuFlyout>
                    </FlyoutBase.AttachedFlyout>
                    <TextBlock Text="{Binding Name}" />
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>

All works well using the Visual Studio Simulator and touch mode, but I cannot find a way to invoke the context menu using my mouse. Do I have to use a GestureRecognizer to get the context menu to work for the desktop application (as opposed to the tablet version)?

回答1:

I would use the RightTapped event instead so that the context menu shows up when user holds on an item in a touch based device and also when user right clicks with a mouse in a mouse based device:

<Page.Resources>
   <MenuFlyout x:Key="flyout">
     ...
   </MenuFlyout>

</Page.Resources>
...

<ListView ....>
  <ListView.ItemTemplate>
     <DataTemplate>
       <Grid RightTapped="grid_RightTapped">
            ...
       </Grid>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

Then handle the event in code behind:

private void grid_RightTapped(object sender, RightTappedRoutedEventArgs e) { 
   this.flyout.ShowAt(this, e.GetPosition(this));
   e.Handled = true;
}

As you see I've used a shared flyout, you can go with your own way.



回答2:

From what you will find at MSDN:

Holding for mouse and pen/stylus input

Mouse input doesn't produce Holding events by default, no matter how long a mouse button is held down, or which button is held. However, mouse devices and some pen devices can fire RightTapped when a right mouse button or equivalent is pressed and released.

Note There is a way to treat mouse actions as hold actions if you use your own GestureRecognizer and specify HoldWithMouse in settings.

In this case you will probably have to use custom GestureRecognizer or use Pointer events.