uwp-xamlautosuggestsearch-boxcommandbar

How to display a SearchBox in CommandBar


I would like to add a AutoSuggestBox in the CommandBar. However the following code does not make the AutoSuggestBox stretch. I tried setting the HorizontalContentAlignment="Stretch" and HorizontalAlignment="Stretch", but it has no impact. What am I missing?

    <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>

error image


Solution

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

    Setting 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. So actually the parent element is a ContentControl not the CommandBar directly. It seems like the size of ContentControl here is depend on its child size, so that AutoSuggestBox has no space to fill.

    Actually the content area is designed aligned to the left side of the bar. Details see Anatomy of app bars. So I don't recommend you to stretch it. You may consider using other controls as the container of the AutoSuggestBox. If you do want to have stretch effect you may calculate the width of AutoSuggestBox manually. For example:

    <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>