WPF GridViewRowPresenter in an ItemsControl

醉酒当歌 提交于 2019-12-22 07:23:09

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/691339/wpf-gridviewrowpresenter-in-an-itemscontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!