您的位置:首页 > 其它

【WPF】MVVM前台绑定一组RadioButton按钮

2017-01-18 12:08 1261 查看
需求:制作一组RadioButton,像下面这样的效果:



【MVVM】要显示一组RadioButton按钮,想法是Controller层联网获取到数据后,将数据进行处理,然后加到一个ObservableCollection集合中(或者List集合),然后前台准备一个列表控件,绑定这个集合。

最初想法是前台使用一个ItemsControl控件,然后设置它的DataTemplate,大致如下:

<ItemsControl x:Name="areaIC" ItemsSource="{Binding AreaNumList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding areaVal}" GroupName="area" Style="{StaticResource myRadioButton2}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</<ItemsControl>


然后,运行后看不到这组按钮,但可以点击。去掉Style属性就只能显示RadioButton左边的圆圈,右边文字Content内容为空,而且按钮组无法切换,问题很多。。。。。

搜了一下解决方案,看到下面这个:

http://stackoverflow.com/questions/5891924/wpf-mvvm-radio-buttons-on-itemscontrol

根据老外的建议,应该使用ListBox而不是ItemsControl ,并且还得设置各种依赖属性的数据源,最后改为如下:

<ListBox x:Name="areaLB" ItemsSource="{Binding AreaNumList}" SelectedItem="{Binding SelectedItem}" BorderThickness="0" Background="White">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton x:Name="radioBtn" FontSize="14" GroupName="area" Style="{StaticResource myRadioButton2}">
<RadioButton.IsChecked>
<Binding Path="IsSelected" RelativeSource="{RelativeSource AncestorType=ListBoxItem}" Mode="TwoWay" />
</RadioButton.IsChecked>
<RadioButton.Content>
<Binding Path="Content" RelativeSource="{RelativeSource AncestorType=ListBoxItem}" Mode="TwoWay" />
</RadioButton.Content>
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  wpf