简体   繁体   English

如何在UWP中的StackPanel中使用ContextFlyout?

[英]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. 在GridView中,当用户右键单击某个项目时,我试图显示一个上下文菜单。

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. 但是StackPanel.ContextFlyout会引发错误。 What I am missing? 我缺少什么?

UPDATE UPDATE

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

ContextFlyout is a property of UIElement, and StackPanel is derived from UIElement. ContextFlyout是UIElement的属性,而StackPanel是从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. 您需要手动管理MenuFlyout,并附带一些代码。

ContextFlyout is a property of UIElement, and StackPanel is derived from UIElement. ContextFlyout是UIElement的属性,而StackPanel是从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. 是的,您是对的,但是请注意,自引入的版本3.0(版本10.0.14393.0)以来,此ContextFlyout属性可用。 What you need is to check your API contract version and device family version. 您需要检查API合约版本和设备系列版本。

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 : 对于@Igor Damiani建议的API合约版本1.0 / 2.0,可以使用FlyoutBase.AttachedFlyout ,并且可以在StackPanelRightTapped事件中获取DataContext

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. 但是我注意到您的MenuFlyoutItem可以更改颜色,实际上需要访问StackPanel内的UIElement或此StackPanel本身。 If so, it's better to bind the color to a property which is implemented INotifyPropertyChanged interface. 如果是这样,最好将颜色绑定到由INotifyPropertyChanged接口实现的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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