确定在执行上下文菜单时单击列表框中的哪个列表框项

本文关键字:列表 单击 执行 上下文 菜单 | 更新日期: 2023-09-27 18:03:43

我试图在列表框中使用上下文菜单来运行一些代码。需要它的来源的数据。点击事件上下文菜单项显示MSG,但我发现它不能访问原始的listview项。

<Canvas x:Name="LeftCanvas"  Grid.Column="0" Grid.Row="1" Margin="5,0,0,0">
    <StackPanel>
        <TextBlock Text="Unseated Guests" Background="Blue" Foreground="White" FontFamily="Verdana" FontSize="11" FontWeight="Bold" Height="17" Width="150" HorizontalAlignment="Left" TextAlignment="Center"  Padding="0,4,5,2"></TextBlock>
        <ListBox x:Name="UnseatedPersons" ItemsSource="{Binding}" Height="218"  Width="150" BorderBrush="Blue" BorderThickness="2" HorizontalAlignment="Left" Padding="3,2,2,2" src:FloorPlanClass.DragEnabled="true" MouseEnter="UnseatedPersons_MouseEnter"
             MouseLeave="SourceListBox_MouseLeave">
            <ListBox.ItemTemplate>
                <DataTemplate>
                        <DockPanel>
                            <DockPanel.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="Archive Info" Click="bt_click" />
                                    <MenuItem Header="Guest Info" />
                                </ContextMenu>
                            </DockPanel.ContextMenu>
                            <Image Name="imgPerson" Source="{Binding ImagePath}" />
                            <TextBlock Name="txtPersonName" Text="{Binding PersonName}" Padding="2,4,0,0" />
                        </DockPanel>
                    </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>            
</Canvas>
c#:

void bt_click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("my message");
}

确定在执行上下文菜单时单击列表框中的哪个列表框项

通过将它们强制转换为MenuItem来使用发送方。如:

void bt_click(object sender, RoutedEventArgs e) 
{ 
    MenuItem originalItem = (MenuItem)sender;
    MessageBox.Show(string.Format("clicked from '"{0}'"", originalItem.Name)); 
}
  1. 点击事件中的发送者将是您点击的MenuItem
  2. 父节点为ContextMenu
  3. ContextMenuPlacementTarget将成为DockPanel
  4. DockPanel将把ListBoxItem作为可视化树的祖先

要在点击事件中获取ListBoxItem你可以使用类似的代码

private void bt_click(object sender, RoutedEventArgs e)
{
    MenuItem clickedMenuItem = sender as MenuItem;
    ContextMenu contextMenu = clickedMenuItem.Parent as ContextMenu;
    DockPanel dockPanel = contextMenu.PlacementTarget as DockPanel;
    ListBoxItem listBoxItem = GetVisualParent<ListBoxItem>(dockPanel);
    MessageBox.Show(listBoxItem.ToString());
    // Update. To display the content of the ListBoxItem
    MessageBox.Show(listBoxItem.Content.ToString());
}
public static T GetVisualParent<T>(object childObject) where T : Visual
{
    DependencyObject child = childObject as DependencyObject;
    // iteratively traverse the visual tree
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}