gpt4 book ai didi

windows-phone-7 - Windows 手机中列表的上下文菜单

转载 作者:行者123 更新时间:2023-12-04 06:55:38 24 4
gpt4 key购买 nike

首先,我知道这个话题: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>

我是这样填写 list 的:
this.friendsListBox.Items.Add(friend.serviceName);

但是,当然,当我长按时,上下文菜单会出现并选择整个列表,而不仅仅是一项。

是否有一些简单的方法可以识别被点击的项目?
谢谢

顺便说一句,我找到了这个方法,但是 contextMenuListItem 没有收到任何东西,它仍然为空:
ListBoxItem contextMenuListItem = friendsListBox.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;

最佳答案

您应该将 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]);
}

希望这可以帮助。

关于windows-phone-7 - Windows 手机中列表的上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16187662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com