0

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

在构造函数中:

listBox1.MouseDown += new MouseButtonEventHandler(listBox1_MouseRightClick);

右键点击:

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");
            }
        }
    }

在xml中:

<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>

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

4

2 回答 2

1

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

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

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

在构造函数中,摆脱这个

listBox1.MouseDown += new MouseButtonEventHandler(listBox1_MouseRightClick);

现在在事件处理程序中,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
      }
}
于 2013-08-19T16:34:28.277 回答
0

右键删除记录不是一个好的设计,它会导致用户更加混淆功能。不过,如果您想做某事,则可以参加PreviewMouseRightButtonDown事件。请看下面的片段

ListBox1.PreviewMouseRightButtonDown += new MouseButtonEventHandler(ListBox1_MouseRightButtonDown);

如下更改您的 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>
于 2013-08-19T15:26:04.390 回答