简体   繁体   中英

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:

列表框

Thx

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM