Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - DataTemplate without a container, items as rows in a Grid?

Is there an equivalent mechanism to the ItemsControl.ItemTemplate that works with a Grid? I have a collection of items and I'd like to present them as rows in a Grid so that I can assign Grid.Column to the individual elements inside the template (as opposed to rows in a list control). Is this possible in WPF using standard controls?

like image 448
Rich Avatar asked Dec 03 '25 00:12

Rich


2 Answers

Ok, use an ItemsControl with the Grid.IsSharedSizeScope="true" attached property applied. Next, for your your ItemTemplate, you use a <Grid> just like you normally would except now when you add ColumnDefinitions you set the SharedSizeGroup attribute to a name that is unique for each column. So for example:

<ItemsControl Grid.IsSharedSizeScope="true">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition SharedSizeGroup="MyFirstColumn" />
                    <ColumnDefinition SharedSizeGroup="MySecondColumn" />
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding MyFirstProperty}"/ >
                <TextBlock Grid.Column="1" Text="{Binding MySecondProperty}"/ >
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

For more on IsSharedSizeScope and SharedSizeGroup, check out this section of the SDK. It should be noted that RowDefinitions also have a SharedSizeGroup so that you could do horizontal layouts as well.

like image 67
Drew Marsh Avatar answered Dec 05 '25 15:12

Drew Marsh


Maybe I misunderstood your problem, but isn't it exactly what a GridView does ?

like image 45
Thomas Levesque Avatar answered Dec 05 '25 14:12

Thomas Levesque