Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF GridViewRowPresenter in an ItemsControl

I'm just starting learning WPF and I'm trying to use a GridViewRowPresenter inside of an ItemsControl to essentially duplicate the functionality of a simple table in HTML. The ListView is not appropriate since it is interactive (which I don't want). I am binding to a generic List of objects of an unknown quantity.

I have a List of a custom object that has two string properties: FirstName and LastName. The following code works:

<ItemsControl Name="myItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=FirstName}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

while this renders nothing:

<ItemsControl Name="myItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <GridViewRowPresenter>
                <GridViewRowPresenter.Columns>
                    <GridViewColumnCollection>
                        <GridViewColumn DisplayMemberBinding="{Binding Path=FirstName}"></GridViewColumn>
                        <GridViewColumn DisplayMemberBinding="{Binding Path=LastName}"></GridViewColumn>
                    </GridViewColumnCollection>
                </GridViewRowPresenter.Columns>
            </GridViewRowPresenter>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

I'm not sure where to go from here and I would greatly appreciate any help! Thanks!

like image 298
DrBoom Avatar asked Mar 27 '09 20:03

DrBoom


1 Answers

If you want a non-interactive grid of items, you can use an ItemsControl with a Grid that uses shared size scope:

<ItemsControl ItemsSource="{Binding Items}" Grid.IsSharedSizeScope="True">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" SharedSizeGroup="FirstName"/>
                    <ColumnDefinition Width="*" SharedSizeGroup="LastName"/>
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Grid.Column="1" Text="{Binding LastName}"/>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

A more efficient approach would be to write your own Panel subclass that works similarly to Grid (you could probably subclass Grid) but automatically adds rows as necessary. Then use that Panel as the ItemsPanel for the ItemsControl.

like image 175
Kent Boogaart Avatar answered Nov 15 '22 06:11

Kent Boogaart