user547995
user547995

Reputation: 2085

Controls vertical alignment with grid on the left and right

I have a custom listbox with a label and a checkbox in each row. I would like to have the label on the far left and the checkbox on the far right.

approach:

<ListBox x:Name="lbFieldsreq" HorizontalAlignment="Left" Height="100" Margin="513,232,0,0" VerticalAlignment="Top" Width="100">
      <ListBox.ItemTemplate>
           <DataTemplate>
                        <Grid ShowGridLines="True">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Label Content="{Binding name, Mode=OneWay}" Grid.Column="0" HorizontalAlignment="Left" />
                            <Label  Grid.Column="1" HorizontalAlignment="Center" /> <!--Empty column -->
                            <CheckBox IsChecked="{Binding ticked  ,Mode=OneWay}" Grid.Column="2" HorizontalAlignment="Right" />
                        </Grid>
           </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

current look:

listbox

Thx

Upvotes: 1

Views: 891

Answers (1)

Sheridan
Sheridan

Reputation: 69959

Your XAML is mostly fine. All you really need to do is to set the ListBox.HorizontalContentAlignment property to "Stretch". This basically forces each item in the collection to stretch to fill with entire Width of the related ListBoxItem. However, you could improve this further by setting the Grid.IsSharedSizeScope Attached Property to True. Setting this in conjunction with the SharedSizeGroup property enables us to ensure that the column Widths of each column of the DataTemplate are the same. Try this:

<ListBox x:Name="lbFieldsreq" HorizontalAlignment="Left" Height="100" ItemsSource="{Binding Items}" VerticalAlignment="Top" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid ShowGridLines="True" Grid.IsSharedSizeScope="True">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="LabelColumn" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" SharedSizeGroup="CheckBoxColumn" />
                </Grid.ColumnDefinitions>
                <Label Content="{Binding}" Grid.Column="0" HorizontalAlignment="Left"  />
                <!--Empty column -->
                <Label Grid.Column="1" HorizontalAlignment="Center" />
                <CheckBox Grid.Column="2" IsChecked="{Binding ticked, Mode=OneWay}" HorizontalAlignment="Right" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 3

Related Questions