ListBox中的水平单选按钮

时间:2013-01-18 19:02:16

标签: wpf mvvm

我很难让这个工作起来。代码位于MVVM应用程序中,我将单选按钮绑定到ViewModel中的属性。

我正在尝试实施此SO回答https://stackoverflow.com/a/2285732

一切正常,但按钮是垂直堆叠的。现在,这似乎是一个简单的修复,只需修改ItemsPanelTemplate。

这是我的代码:

<ListBox ItemsSource="{Binding ItemOptions}" SelectedItem="{Binding SelectedOption}">
     <ListBox.ItemsPanel>
          <ItemsPanelTemplate>
               <StackPanel Orientation="Horizontal" IsItemsHost="True" />
          </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
     <ListBox.ItemContainerStyle>
          <Style TargetType="{x:Type ListBoxItem}">
               <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}"  >
                            <RadioButton Content="{TemplateBinding Content}" 
                                 IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
           </Style>
     </ListBox.ItemContainerStyle>
</ListBox>

然而,物品仍然垂直堆放。任何想法为什么这对ListBox的方向没有影响?我错过了什么?

谢谢, 杰里

2 个答案:

答案 0 :(得分:3)

试试这个:

            <ListBox.Template>
                <ControlTemplate TargetType="{x:Type ListBox}">
                      <ScrollViewer x:Name="scrollviewer" HorizontalScrollBarVisibility="Visible" CanContentScroll="False">
                        <StackPanel IsItemsHost="True" Orientation="Horizontal" />
                      </ScrollViewer>
                </ControlTemplate>
            </ListBox.Template>

我尝试使用ItemsPanelTemplate,就像你一样,没有成功。这对我很有用,希望它对你也有帮助!

此致

答案 1 :(得分:0)

这是一个没有样式的基本示例。请注意,WrapPanel处理布局。

    <ListBox Margin="0,10,0,0"        
             ItemsSource="{StaticResource Orders}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel HorizontalAlignment="Stretch"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <RadioButton Content="{Binding CustomerName}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

具有后面代码中定义的模型的数据。

<Page.Resources>
    <model:Orders x:Key="Orders">
        <model:Order CustomerName="Alpha"
                    OrderId="997"
                    InProgress="True" />
        <model:Order CustomerName="Beta"
                    OrderId="998"
                    InProgress="False" />
        <model:Order CustomerName="Omega"
                    OrderId="999"
                    InProgress="True" />
        <model:Order CustomerName="Zeta"
                    OrderId="1000"
                    InProgress="False" />
    </model:Orders>
</Page.Resources>

结果

enter image description here