控制左右两侧的网格垂直对齐

时间:2014-07-22 07:24:50

标签: c# wpf xaml wpf-controls

我有一个带有标签的自定义列表框,每行都有一个复选框。我想在最左边的标签和最右边的复选框。

方法

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

当前外观:

listbox

THX

1 个答案:

答案 0 :(得分:3)

你的XAML很好。您真正需要做的就是将ListBox.HorizontalContentAlignment property设置为"Stretch"。这基本上会强制集合中的每个项目进行拉伸,以填充相关Width的整个ListBoxItem。但是,您可以通过将Grid.IsSharedSizeScope Attached Property设置为True来进一步改进。与SharedSizeGroup属性一起设置此选项使我们能够确保Width的每列的DataTemplate列相同。试试这个:

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