views:

587

answers:

2

I have an items control that is bound to a collection of objects. The object has two properties (name, value) that i display in a textblock and textbox respectively. The list is quite long and I would like to show it in two columns. So my question is, is there any way I can get an Itemscontrol to show its items in two columns?

P.S: The collection is populated at runtime and I dont know how many items I will have to show!

+3  A: 

I tend to put the items in WrapPanel, and then set the width of the panel to be 2x the item width. That gives me nice columns with an arbitrary number of elements. If your item widths differ, I put each item in its own Grid or StackPanel of fixed width.

Dave Markle
Thanks for the answer. I'll try it out. But I have a suspicion that this will mess up my UI when the user resizes the pane/window. Isnt there a more elegant way of doing this? Maybe by using a grid within the itemstemplate of the itemscontrol??
Pradeep
+2  A: 

Use a ListBox and specify a DataTemplate in which you put both the TextBlock and TextBox. Use bindings to populate them both. See http://msdn.microsoft.com/en-us/library/ms742521.aspx for more examples.

<ListBox x:Name="TheListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding Name}" />
                <TextBox Grid.Column="1" Text="{Binding Value }" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

TheListBox.ItemsSource = CollectionOfObjects;
Lars Truijens
The really critical (and non-intuitive, I feel) element of this pattern is SharedSizeGroup. I say "non-intuitive" because you intuitively think "I want to display my items in a grid," not "I want to display my items in many grids whose columns all resize interdependently.
Robert Rossney
When I tried this on an ItemsControl (not a ListBox), I had to set a property on the ItemsControl: Grid.IsSharedSizeScope="True" to make this work.
Scott Whitlock