我的页面中有一个ListBox,我希望ListBox中的一些项目可以在你长按它时弹出ContextMenu,而某些项目不是,我如何以编程方式实现这个需求?
答案 0 :(得分:0)
这是一种可能的解决方案。使用弹出窗口的一些信息定义您的Item类:
public class Item
{
public string Info { get; set; }
// Menu attached or not
public bool OptionsEnabled { get; set; }
}
在XAML中,您必须使用适当的 ItemTelplate 定义 ListView (或 ListBox ):
<ListView Name="myList" Holding="myList_Holding">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Info}" FontSize="24" Margin="7">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="First option"/>
<MenuFlyoutItem Text="Second option"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
然后在举办活动时,您可以查看 OptionsEnabled 属性是否显示菜单,如果是,则执行此操作:
private void myList_Holding(object sender, HoldingRoutedEventArgs e)
{
if (e.OriginalSource == null || !(e.OriginalSource is TextBlock)) return;
TextBlock listItem = e.OriginalSource as TextBlock;
if (listItem.DataContext == null) return;
Item itemData = listItem.DataContext as Item;
if (itemData.OptionsEnabled)
FlyoutBase.ShowAttachedFlyout(listItem);
}
您可以download here的工作样本。