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

时间:2011-07-27 03:22:48

标签: c# wpf xaml listbox contextmenu

我正在尝试使用列表框中的上下文菜单来运行一些来源代码。这需要来自哪个项目的数据。单击事件上下文菜单项显示了msg,但我发现它不会访问原始列表视图项。< / p>

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

2 个答案:

答案 0 :(得分:2)

通过将发件人转发给MenuItem来使用发件人。像:

void bt_click(object sender, RoutedEventArgs e) 
{ 
    MenuItem originalItem = (MenuItem)sender;
    MessageBox.Show(string.Format("clicked from \"{0}\"", originalItem.Name)); 
}

答案 1 :(得分:1)

  1. 点击事件中的发件人将是您点击的MenuItem
  2. 其父级将是ContextMenu
  3. PlacementTarget的{​​{1}}将是ContextMenu
  4. DockPanelDockPanel作为Visual Tree中的祖先
  5. 因此,要在点击事件中获取ListBoxItem,您可以使用与此类似的内容

    ListBoxItem