如何将CheckBox放在WPF中ListBox中的不同行/列中?

时间:2015-12-11 18:56:27

标签: wpf xaml listview listbox itemspaneltemplate

在我的WPF桌面应用程序中,我有一个ListBox,我希望显示两行和两列(即一个2x2网格),在四个行/列的每个点都有一个复选框 - 我的XAML代码是下面。请注意,我不想做任何数据绑定。下面的代码可行,但显示的是所有四个CheckBox都在彼此之上,即使我已经指定它们应该在不同的行/列中。有人能指出我做错了什么以及如何纠正XAML?我在互联网上找到的每个例子都是一个数据绑定的例子,这需要没有数据绑定(即显式)。

<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>

1 个答案:

答案 0 :(得分:0)

你在滥用ListBoxListBox是一个ItemsControl,你并没有真正处理绑定项,所以你应该使用不同的控件来实现你的解决方案。以下内容应该有效:

<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>

如果您希望内容可滚动,请在ScrollViewer周围包裹WrapPanel并在其上设置高度。

证明:

enter image description here

注意:我强烈建议您尽可能使用数据绑定。