3

まず第一に、私はこのトピックについて知っています: How to make context menu work for 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);

しかしもちろん、ロングタップすると、コンテキスト メニューが表示され、1 つの項目だけでなく、リスト全体が選択されます。

アイテムがタップされたことを認識する簡単な方法はありますか? ありがとう

ところで、このメソッドを見つけましたが、contextMenuListItem は何も受信しません。まだ null です。

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

1 に答える 1

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

お役に立てれば。

于 2013-04-24T10:34:32.773 に答える