2011-05-13 93 views
0

基本上我有一个用户控件中的单选按钮集合。我希望这些与ViewModel中的列表保持一致。将WPF单选按钮绑定到ViewModel中的RadioButton`

目前我必须将每个属性的几乎所有属性都绑定到ViewModel集合中的适用索引。 E.g:

<RadioButton x:Name="btnStatus2" IsChecked="{Binding Path=radioButtonsIsChecked, Mode=TwoWay}" 
        Content="{Binding Path=StatusButtonList[1].Content, Mode=TwoWay}" 
        Tag="{Binding Path=StatusButtonList[1].Tag, Mode=TwoWay}" 
        Visibility="{Binding Path=StatusButtonList[1].Visibility, Mode=OneWay}" 
        GroupName="statusBtns" Grid.Column="1" Grid.Row="0" > 

正如你所看到的视图将是相当大的,如果我在我的控制10个单选按钮。我很新的WPF和任何意见将不胜感激。谢谢!

回答

1

使用ItemsControl并将ItemsSource属性设置为viewmodel中的集合。

<ItemsControl ItemsSource="{Binding Path=RadioButtons}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <RadioButton IsChecked="{Binding Path=IsRadioButtonChecked}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

WPF中还有ItemsControl的特殊派生类型,它们提供了附加功能(滚动,选定项目等)。 ListView,ListBox,ComboBox,DataGrid,TreeView等都是ItemsControls,你也可以在这里使用

+0

好的,谢谢你的好友。看起来这是最好的解决方案,但是将这些项目安装到网格中是一个挑战,因为其中有10个。这是我挂上的部分。我想我可以编程指定网格值?原谅我的周五下午的感受.. – JBeagle 2011-05-13 14:42:08

+0

一个ItemsControl有一个ItemsPanelTemplate属性,它指定了项目的布局。默认情况下,它使用StackPanel,所以你不需要在你的RadioButton上指定Grid.Column和Grid.Row。 RadioButtons将相互叠加 – kenwarner 2011-05-13 15:34:24

+0

'WrapPanel'或'UniformGrid'可能是不错的选择。 – svick 2011-05-13 18:15:33