2013-04-24 4 views
3

Прежде всего, я знаю об этой теме: How to make context menu work for windows phone?Контекстное меню для списка в Windows Phone

Но этот путь СОО сложно ... Так что у меня этот код XAML:

<StackPanel Name="friendsGrid" Margin="0,0,0,0" Background="Transparent"> 
    <ListBox Name="friendsListBox" FontSize="32" Tap="friendsListBox_Tap"> 
    <toolkit:ContextMenuService.ContextMenu> 
    <toolkit:ContextMenu Name="MyContextMenu" Opened="MyContextMenu_Opened"> 
    <toolkit:MenuItem Header="action" Click="contextMenuAction_Click"/> 
    </toolkit:ContextMenu> 
    </toolkit:ContextMenuService.ContextMenu> 
    </ListBox> 
</StackPanel> 

И я заполняю список, как это:

this.friendsListBox.Items.Add(friend.serviceName); 

Но, конечно, когда я longtap, контекстное меню появляется и выбирает весь список, а не только один элемент.

Есть ли какой-нибудь простой способ распознавания предмета? Благодаря

BTW, я нашел этот метод, но contextMenuListItem ничего не Получать, он по-прежнему нулевой:

ListBoxItem contextMenuListItem = friendsListBox.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem; 
+0

Можете ли вы показать нам свой список itemtemplate –

ответ

14

Вы должны поставить ContextMenu блок в ваш ItemTemplate (не ListBox блок). Здесь короткий образец.
XAML:

  <ListBox Name="TestList" Margin="26,0,26,0" Height="380" > 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding}"> 
         <toolkit:ContextMenuService.ContextMenu> 
          <toolkit:ContextMenu Name="ContextMenu" > 
           <toolkit:MenuItem Name="Edit" Header="Edit" Click="Edit_Click"/> 
           <toolkit:MenuItem Name="Delete" Header="Delete" Click="Delete_Click"/> 
          </toolkit:ContextMenu> 
         </toolkit:ContextMenuService.ContextMenu> 
        </TextBlock> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

Код:

public List<string> Items = new List<string> 
    { 
     "Item1", 
     "Item2", 
     "Item3", 
     "Item4", 
     "Item5", 
    }; 

    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
     TestList.ItemsSource = Items; 
    } 

    private void Edit_Click(object sender, RoutedEventArgs e) 
    { 
     if (TestList.ItemContainerGenerator == null) return; 
     var selectedListBoxItem = TestList.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem; 
     if (selectedListBoxItem == null) return; 
     var selectedIndex = TestList.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem); 
     MessageBox.Show(Items[selectedIndex]); 
    } 

Надеется, что это помогает.

+0

Вопроситель даже не поддержал решение своей проблемы ... ламе. –

Смежные вопросы