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);
}
posted @ 2011-11-20 17:04  博琼  阅读(636)  评论(0编辑  收藏  举报