为什么右键单击事件在 WPF 中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18317124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:28:03  来源:igfitidea点击:

Why right click event not worked in WPF?

c#wpflistboxitemright-click

提问by user2622971

I want to delete my listbox item on right click. But, right click event not worked in my case. Below is the code which I tried.

我想在右键单击时删除我的列表框项目。但是,右键单击事件在我的情况下不起作用。下面是我试过的代码。

In constructor:

在构造函数中:

listBox1.MouseDown += new MouseButtonEventHandler(listBox1_MouseRightClick);

Right Click:

右键点击:

private void listBox1_MouseRightClick(object sender, MouseButtonEventArgs e)
    {
        if (sender is ListBoxItem)
        {
            ListBoxItem item = (ListBoxItem)sender;
            Harvest_TimeSheetEntry entryToDelete = (Harvest_TimeSheetEntry)item.DataContext;

            MessageBoxResult Result = System.Windows.MessageBox.Show("Are you sure?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);

            if (Result == MessageBoxResult.Yes)
            {
                Globals._globalController.harvestManager.deleteHarvestEntry(entryToDelete);
            }
            else
            {
                System.Windows.MessageBox.Show("Delete operation Terminated");
            }
        }
    }

In xaml:

在 xaml 中:

<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" SelectionMode="Single" MouseRightButtonDown="listBox1_MouseRightClick">
    <ListBox.ItemContainerStyle>
       <Style TargetType="{x:Type ListBoxItem}">
           <EventSetter Event="MouseDown" Handler="listBox1_MouseRightClick"/>
       </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Please suggest, how should I use right click event so it could work?

请建议,我应该如何使用右键单击事件才能使其工作?

回答by Shoe

Your original code seems redundant and verbose. MouseRightButtonDownisn't working because there is already an event handling listbox item selection and the ListBoxItemdatacontext is simply the SelectedItemof listBox1.

您的原始代码似乎多余且冗长。MouseRightButtonDown不起作用,因为已经有一个事件处理列表框项目选择,并且数据上下文ListBoxItem只是SelectedItemlistBox1 的。

Get rid of overriding the style and just declare the listbox with the preview event. This will tunnel MouseRightButtonDowninstead of bubble it.

摆脱覆盖样式,只需使用预览事件声明列表框。这将隧道MouseRightButtonDown而不是气泡。

<ListBox x:Name="listBox1"
         ItemsSource="{Binding}"
         ItemTemplateSelector="{StaticResource templateSelector}"
         Margin="0,131,0,59"
         SelectionMode="Single" 
         PreviewMouseRightButtonDown="listBox1_MouseRightClick" />

In the constructor, get rid of this

在构造函数中,去掉这个

listBox1.MouseDown += new MouseButtonEventHandler(listBox1_MouseRightClick);

Now in the event handler, senderis your listbox1 but if you're not tying this event to other listboxes, simply get the selectedItem from listbox1 and cast it to the appropriate object. Otherwise if you decide you want the functionality on multiple listboxes cast senderto ListBox

现在在事件处理程序中,sender是您的 listbox1 但如果您不将此事件绑定到其他列表框,只需从 listbox1 获取 selectedItem 并将其转换为适当的对象。否则,如果您决定要将多个列表框上的功能sender转换为ListBox

private void listBox1_MouseRightClick(object sender, MouseButtonEventArgs e)
{
      Harvest_TimeSheetEntry entryToDelete = (Harvest_TimeSheetEntry)listBox1.SelectedItem;
      if(entryToDelete != null)
      {
          //Do work
      }
}

回答by Vimal CK

Deleting records on right click is not a good design and it leads users make more confuse the functionality. Still if you want to do something, then you can go for the PreviewMouseRightButtonDownevent. Please see the below snippet

右键删除记录不是一个好的设计,它会导致用户更加混淆功能。如果你想做点什么,那么你可以去PreviewMouseRightButtonDown事件。请看下面的片段

ListBox1.PreviewMouseRightButtonDown += new MouseButtonEventHandler(ListBox1_MouseRightButtonDown);

Change your XAML as follows

按如下方式更改您的 XAML

<ListBox x:Name="listBox1"
             ItemsSource="{Binding}"
             Margin="0,131,0,59"
             ItemTemplateSelector="{StaticResource templateSelector}"
             SelectionMode="Single">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <EventSetter Event="PreviewMouseRightButtonDown"
                             Handler="ListBox1_PreviewMouseRightButtonDown" />
            </Style>
        </ListBox.ItemContainerStyle>
</ListBox>