如何在 CommandBar 中显示搜索框

How to display a SearchBox in CommandBar

我想在 CommandBar 中添加一个 AutoSuggestBox。但是,以下代码不会使 AutoSuggestBox 伸展。我尝试设置 HorizontalContentAlignment="Stretch"HorizontalAlignment="Stretch",但没有任何影响。我错过了什么?

    <CommandBar Grid.Row="0" HorizontalContentAlignment="Stretch">
        <CommandBar.Content>
            <AutoSuggestBox HorizontalAlignment="Stretch" Margin="8 8 8 4" PlaceholderText="Search podcasts" QueryIcon="Find">
                <Interactivity:Interaction.Behaviors>
                    <Core:EventTriggerBehavior EventName="QuerySubmitted">
                        <Core:InvokeCommandAction                         
                    Command="{Binding SearchCommand}"
                    InputConverter="{StaticResource QueryArgsConverter}" />
                    </Core:EventTriggerBehavior>
                </Interactivity:Interaction.Behaviors>
            </AutoSuggestBox>
        </CommandBar.Content>
    </CommandBar>

I tried setting the HorizontalContentAlignment="Stretch" and HorizontalAlignment="Stretch", but it has no impact.

设置Horizontal​Alignment to stretch means an element stretched to fill the entire layout slot of the parent element. In your code snippet, the AutoSuggestBox is inside the content of the CommandBar, if we checked the default template of CommandBar, the content of the CommandBar using a Content​Control。所以实际上父元素是 ContentControl 而不是 CommandBar 直接。看起来 ContentControl 的大小取决于它的子大小,所以 AutoSuggestBox 没有 space 可以填充。

实际上,内容区域被设计为与栏的左侧对齐。详情见剖析app bars。所以我不建议你拉伸它。您可以考虑使用其他控件作为 AutoSuggestBox 的容器。如果你确实想要拉伸效果,你可以手动计算 AutoSuggestBox 的宽度。例如:

<CommandBar x:Name="cmdbar">
    <CommandBar.Content>
        <AutoSuggestBox
            x:Name="autobox"
            Width="{Binding ElementName=cmdbar, Path=ActualWidth}"
            HorizontalAlignment="Stretch"
            PlaceholderText="Search podcasts"
            QueryIcon="Find" />
    </CommandBar.Content>
</CommandBar>