UWP:为什么 FlyoutBase.ShowAttachedFlyout 对 Button 失败

UWP: why does FlyoutBase.ShowAttachedFlyout fail for Button

我在 XAML 中声明了一个带有 Button.Flyout 嵌套元素的 Button。我正在点击按钮,然后希望显示弹出窗口。但是我得到一个错误:

ShowAttached was called on an element without an attached FlyoutBase.

这是XAML:

      <Button ... Click="onMoreClicked">
        <Image Source="..." />
        <Button.Flyout > 
         ...
        </Button.Flyout>
      </Button>

而且,这是我的处理程序:

public void onMoreClicked (object sender, RoutedEventArgs e)
{
  Log.L("LP OnMoreClicked");
  Button element = sender as Button;
  FlyoutBase flyout = element.Flyout as FlyoutBase;
  FlyoutBase.ShowAttachedFlyout(element);
}

进入调试器时,元素和浮出控件已定义,即不为空。然而,ShowAttachedFlyout 失败了。

编辑

为清楚起见,使用@AryaDing-MSFT 的答案,这是我的工作解决方案:

<Button ... Click="onMoreClicked">
  <Image Source="..." />
  <FlyoutBase.AttachedFlyout> 
   ...
  </FlyoutBase.AttachedFlyout>
</Button>

处理程序:

public void onMoreClicked (object sender, RoutedEventArgs e)
{
  Button button = sender as Button;
  ... do stuff ...
  FlyoutBase.ShowAttachedFlyout(button);
}

这个问题是因为没有使用FlyoutBase.AttachedFlyout来附加属性,需要使用FlyoutBase.ShowAttachedFlyout和FlyoutBase.AttachedFlyout在一起。

official document, if the control doesn't have a flyout property, you can use the FlyoutBase.AttachedFlyout attached property instead. When you do this, you also need to call the FlyoutBase.ShowAttachedFlyout 方法派生以显示弹出窗口。

所以你可以参考下面的代码

XAML:

<Button Click="onMoreClicked">
    <FlyoutBase.AttachedFlyout>
          <Flyout>
             <TextBlock Text="This is a flyout!"/>
          </Flyout>
    </FlyoutBase.AttachedFlyout>             
</Button>

后面的代码:

private void onMoreClicked(object sender, RoutedEventArgs e)
    {
        FrameworkElement element = sender as FrameworkElement;
        FlyoutBase.ShowAttachedFlyout(element);
    }

因为按钮有flyout属性,也可以像下面这样直接写

<Button>
     <Button.Flyout >
         <Flyout>
            <TextBlock Text="This is a flyout!"/>
          </Flyout>
      </Button.Flyout>
</Button>