简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM