Friday, January 21, 2022

Width=Auto

If you define a UIElement with HorizontalAlignment="Stretch" and a Width, you will find the element does not render the way you want. If you make heavy use of styles, you might need a way to override a style's Width property to allow you to specify a HorizontalAlignment on the element's declaration. It turns out you can do this with Width="Auto". Take a look at the XAML below.

You can see the top text box is ignoring the HorizontalAlignment="Stretch" because of the width defined in the default style. The lower text box uses Width="auto" to override the style's width which allows the HorizontalAlignment="Stretch" to take effect.

<Window x:Class="AutoWidth.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AutoWidth"
        mc:Ignorable="d"
        Title="AutoWidth" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="TextBox">
            <Setter Property="Width" Value="100"/>
            <Setter Property="Background" Value="Yellow"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="200"/>
        </Grid.ColumnDefinitions>
       
        <TextBlock Grid.Row="0" Grid.Column="0" Text="Default Width"/>
        <TextBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch"/>
 
        <TextBlock Grid.Row="1" Grid.Column="0" Text="Width=Auto"/>
        <TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" Width="auto"/>
    </Grid>
</Window>

 



No comments:

Post a Comment