Search code examples
wpfxamllistviewlistboxitemspaneltemplate

How to place CheckBoxes in different rows/columns within a ListBox in WPF?


In my WPF desktop application, I have a ListBox that I would like to display with two rows and two columns (i.e., a 2x2 grid), with a Checkbox in each of the four row/column spots - my XAML code is below. Note that I don't want to do any data binding. The code below works, but what shows up is that all four CheckBoxes are right on top of each other, even though I've specified that they should be in different rows/columns. Could someone point out what I'm doing wrong and how to correct the XAML? Every example I've found on the internet is a data-bound example, and this needs to be without data-binding (i.e., explicit).

<ListBox Margin="0,0,10,10" Name="myListBox" Height="139" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="112" >
    <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50"/>
            <ColumnDefinition Width="50"/>
        </Grid.ColumnDefinitions>
        </Grid>
    </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <CheckBox Content="WCF"  Grid.Row="0" Grid.Column="0"/>
    <CheckBox Content="ASP.NET"  Grid.Row="0" Grid.Column="1"/>
    <CheckBox Content="Java"  Grid.Row="1" Grid.Column="0"/>
    <CheckBox Content="C+"  Grid.Row="1" Grid.Column="1"/>
</ListBox>

Solution

  • You're misusing ListBox. ListBox is an ItemsControl and you're not really dealing with bound items, so you should use a different control to achieve your solution. Something like the following should work:

    <ScrollViewer Height="50"
                  HorizontalAlignment="Center">
        <WrapPanel Width="150">
            <CheckBox Name="Wcf"
                      Content="WCF"
                      Width="75" />
            <CheckBox Name="Asp"
                      Content="ASP.NET"
                      Width="75" />
            <CheckBox Name="Java"
                      Content="Java"
                      Width="75" />
            <CheckBox Name="WhatIsThis"
                      Content="C+"
                      Width="75" />
            <CheckBox Content="WCF"
                      Width="75" />
            <CheckBox Content="ASP.NET"
                      Width="75" />
            <CheckBox Content="Java"
                      Width="75" />
            <CheckBox Content="C+"
                      Width="75" />
            <!-- add as many items as you want -->
        </WrapPanel>
    </ScrollViewer>
    

    If you want the content to be scroll-able, then wrap a ScrollViewer around your WrapPanel and set height on it.

    Proof:

    enter image description here

    Note: I highly advise you to use data binding whenever it is possible.