简体   繁体   中英

Binding Grid column width


I am facing the following problem in the design of my XAML.

I need to arrive at the end to arrange my data like a grid but with a custom DataTemplate . So I create a top Grid which contains the two header lables of the data items. Below the Grid I build a StackPanel with an ItemsControl which includes the DataTemplate which displays my data. Everything is ok, when I run the application I get the header lables and the data items below like a grid. My problem is that the labels and the content of the items are not aligned correctly. So I thought about binding the Width of the header lable columns to the ActualWidth of the ItemTemplate , but unfortunately that does not work.

Is there any clean way to achive this?
Thanks in advance ...

There is a easy way to do this using SharedSizeGroup in the grid columns and assinging Grid.IsSharedSizeScope="True" for the parent.

eg

    <StackPanel Grid.IsSharedSizeScope="True">
        <Grid Name="Headers">
            <Grid.ColumnDefinitions>
                <ColumnDefinition SharedSizeGroup="A"/>
                <ColumnDefinition SharedSizeGroup="B"/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" Text="Name"/>
            <TextBlock Grid.Column="1" Text="Occupation"/>
        </Grid>
        <ItemsControl Name="Items" ItemsSource="{Binding Data}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition SharedSizeGroup="A"/>
                            <ColumnDefinition SharedSizeGroup="B"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding Name}"/>
                        <TextBlock Grid.Column="1" Text="{Binding Occupation}"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>

All the items will have the same widths in the columns, the only thing that you might need to line up manually is the headers section above the items, depending on margin settings and the like.

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