You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让DropDownButton的Flyout在选中条目后自动关闭

问题根因

你的代码存在两个核心问题导致异常:

  • 调用对象错误:Hide()是Flyout类的方法,ListView本身没有该方法,不能直接操作ListView执行隐藏
  • 触发时机冲突:页面初始化阶段绑定SelectedItem会自动触发一次SelectionChanged事件,此时Flyout尚未打开,直接执行隐藏逻辑会导致状态异常

实现方案(两种可选)

方案1:给Flyout命名直接操作(写法最简洁)

修改XAML,给Flyout添加名称标识

<DropDownButton Content="{x:Bind CurrentMode, Mode=OneWay}" >
    <DropDownButton.Flyout>
        <!-- 新增x:Name属性 -->
        <Flyout x:Name="ModeSelectFlyout">
            <ListView x:Name="testListView" ItemsSource="{x:Bind mDropdownItems, Mode=OneWay}" 
                      SelectionMode="Single" SelectedItem="{x:Bind CurrentMode, Mode=TwoWay}"
                      SelectionChanged="OnSelectionChanged" >
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="x:String">
                        <TextBlock Text="{x:Bind}"></TextBlock>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Flyout>
    </DropDownButton.Flyout>
</DropDownButton>

修改后台事件逻辑,增加状态判断

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // 过滤初始化阶段无实际选中项变更的空回调
    if (e.AddedItems.Count == 0) return;

    // 仅当Flyout处于打开状态时才执行关闭操作
    if (ModeSelectFlyout.IsOpen)
    {
        ModeSelectFlyout.Hide();
    }

    NotifyPropertyChanged(nameof(CurrentMode));
}

方案2:无需给Flyout命名,通过DropDownButton关联获取

修改XAML,仅给DropDownButton添加名称标识

<!-- 新增x:Name属性 -->
<DropDownButton x:Name="ModeSelectDropDown" Content="{x:Bind CurrentMode, Mode=OneWay}" >
    <DropDownButton.Flyout>
        <Flyout>
            <ListView x:Name="testListView" ItemsSource="{x:Bind mDropdownItems, Mode=OneWay}" 
                      SelectionMode="Single" SelectedItem="{x:Bind CurrentMode, Mode=TwoWay}"
                      SelectionChanged="OnSelectionChanged" >
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="x:String">
                        <TextBlock Text="{x:Bind}"></TextBlock>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Flyout>
    </DropDownButton.Flyout>
</DropDownButton>

修改后台事件逻辑

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count == 0) return;

    // 从DropDownButton中获取关联的Flyout实例
    if (ModeSelectDropDown.Flyout is Flyout flyout && flyout.IsOpen)
    {
        flyout.Hide();
    }

    NotifyPropertyChanged(nameof(CurrentMode));
}

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 11:51:03