Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use ContextFlyout in a StackPanel in UWP?

In a GridView, I am trying to show a context menu when the user right clicks an item.

I tried:

 <GridView.ItemTemplate>
    <DataTemplate>
       <StackPanel Orientation="Vertical" Width="120" Background="LightBlue">
       <StackPanel.ContextFlyout>
             <MenuFlyout>
                  <MenuFlyoutItem Text="Change color" Click="ChangeColorItem_Click" />
             </MenuFlyout>
...

But StackPanel.ContextFlyout throws an error. What I am missing?

UPDATE

The error is: The attachable property 'ContextFlyout' was not found in type 'StackPanel'

ContextFlyout is a property of UIElement, and StackPanel is derived from UIElement.

like image 994
kokokok Avatar asked Sep 19 '25 12:09

kokokok


2 Answers

ContextFlyout is a property of UIElement, and StackPanel is derived from UIElement.

Yes you are right, but be careful that this ContextFlyout property is available since the introduced version 3.0, version 10.0.14393.0. What you need is to check your API contract version and device family version.

For API contract version 1.0/2.0, as @Igor Damiani suggested, you can use FlyoutBase.AttachedFlyout, and you can get the DataContext for example in the RightTapped event of the StackPanel:

private void StackPanel_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
    FlyoutBase.ShowAttachedFlyout(sender as StackPanel);
    var datacontext = ((FrameworkElement)e.OriginalSource).DataContext;
}

But I noticed that your MenuFlyoutItem is possible for color changing, what you need is actually access to the UIElements inside the StackPanel or this StackPanel itself. If so, it's better to bind the color to a property which is implemented INotifyPropertyChanged interface.

like image 98
Grace Feng Avatar answered Sep 22 '25 03:09

Grace Feng


Try this:

   <DataTemplate>
      <StackPanel Orientation="Vertical" Width="120" Background="LightBlue">
         <FlyoutBase.AttachedFlyout>
            <MenuFlyout>
                <MenuFlyoutItem Text="Change color" Click="ChangeColorItem_Click" />
            </MenuFlyout>
         </FlyoutBase.AttachedFlyout>
      </StackPanel>
   </DataTemplate>

You need to manually manage the MenuFlyout with a little code-behind.

like image 37
Igor Damiani Avatar answered Sep 22 '25 02:09

Igor Damiani