ContextMenu 中获得选中的 Item

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    string header = (sender as MenuItem).Header.ToString();
 
    ListBoxItem selectedListBoxItem = this.listBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
    if (selectedListBoxItem == null)
    {
        return;
    }
 
    if (header == "Add Color")
    {
        selectedListBoxItem.Background = new SolidColorBrush(Colors.Red);
    }
    else
    {
        selectedListBoxItem.Background = new SolidColorBrush(Colors.Black);
    }
 
    //To highlight the tapped item just use something like selectedListBoxItem.Background = new SolidColorBrush(Colors.Green);
}
原文地址:https://www.cnblogs.com/hebeiDGL/p/2256281.html