I am working on Windows 10 UWP app and came across a long press menu in Photos app as below
Can someone suggest how to create this type of menu in Windows 10?
I checked PopupMenu control but it only allows 6 options in the menu.I want to create this menu using C# not XAML.
You can use Flyout for this purpose, then in item's datatemplate, define subscripe to event and show your menu. A sample can look like this:
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Holding="Grid_Holding" VerticalAlignment="Stretch">
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem x:Name="EditButton" Text="Edit"/>
<MenuFlyoutItem x:Name="DeleteButton" Text="Delete"/>
<MenuFlyoutSubItem Text="OtherItems">
<MenuFlyoutItem Text="Inside1"/>
<MenuFlyoutItem Text="Inside2"/>
<MenuFlyoutItem Text="Inside3"/>
</MenuFlyoutSubItem>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<TextBlock Text="{Binding}" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<x:String>Item 1</x:String>
<x:String>Item 2</x:String>
<x:String>Item 3</x:String>
<x:String>Item 4</x:String>
<x:String>Item 5</x:String>
</ListView>
And the code behind:
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
FrameworkElement senderElement = sender as FrameworkElement;
// If you need the clicked element:
// Item whichOne = senderElement.DataContext as Item;
FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
}
As a result you should see something like in the picture below.
Some more help you will also find at MSDN.
Edit after comments.
Generally everything you create in XAML can be created in code behind. If you want to create a Flyout, then it can look like this:
private bool startedHolding = false;
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
// simple checkup for holding release for this sample, though this probalby need better handling
startedHolding = !startedHolding;
if (startedHolding)
{
MenuFlyout myFlyout = new MenuFlyout();
MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "First item" };
MenuFlyoutItem secondItem = new MenuFlyoutItem { Text = "Second item" };
MenuFlyoutSubItem subItem = new MenuFlyoutSubItem { Text = "Other items" };
MenuFlyoutItem item1 = new MenuFlyoutItem { Text = "First sub item" };
MenuFlyoutItem item2 = new MenuFlyoutItem { Text = "Second sub item" };
subItem.Items.Add(item1);
subItem.Items.Add(item2);
myFlyout.Items.Add(firstItem);
myFlyout.Items.Add(secondItem);
myFlyout.Items.Add(subItem);
FrameworkElement senderElement = sender as FrameworkElement;
myFlyout.ShowAt(senderElement);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With