【问题标题】:How use ContextFlyout in a StackPanel in UWP?如何在 UWP 的 StackPanel 中使用 ContextFlyout?
【发布时间】:2016-07-29 12:25:56
【问题描述】:

在 GridView 中,我试图在用户右键单击项目时显示上下文菜单。

我试过了:

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

但是StackPanel.ContextFlyout 会引发错误。我错过了什么?

更新

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

ContextFlyout 是 UIElement 的一个属性,StackPanel 是从 UIElement 派生的。

【问题讨论】:

  • 哪个错误?你有什么消息吗?请张贴出来。

标签: c# xaml uwp uwp-xaml


【解决方案1】:

ContextFlyout 是 UIElement 的一个属性,StackPanel 是从 UIElement 派生的。

是的,您是对的,但请注意,此 ContextFlyout 属性自引入的版本 3.0 版本 10.0.14393.0 起可用。您需要检查您的 API 合同版本和设备系列版本。

对于 API 合约版本 1.0/2.0,正如@Igor Damiani 建议的那样,您可以使用FlyoutBase.AttachedFlyout,并且您可以在StackPanelRightTapped 事件中获取DataContext

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

但我注意到您的MenuFlyoutItem 可以更改颜色,您实际上需要访问StackPanel 或这个StackPanel 本身内的UIElements。如果是这样,最好将颜色绑定到实现INotifyPropertyChanged接口的属性。

【讨论】:

  • 在 UserControl 中使用它并添加 MenuFlyoutSubItem 时,子菜单在超出窗口时似乎会被切断
  • @Arlo,AFAIK,根据设计,所有 UI 元素都应包含在 UWP 应用程序的框架内,如果您想在另一个窗口中显示对话框,您可以参考我在此问题中的回答: make a content Dialog movable like the one in the Groove app.
  • 实际上我可以通过使上下文菜单显示在指针下而不是元素上来解决它
【解决方案2】:

试试这个:

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

您需要手动管理 MenuFlyout,并使用一些代码隐藏。

【讨论】:

  • 尽管不直观,但这是正确的语法
猜你喜欢
  • 2019-08-04
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
相关资源
最近更新 更多