zoukankan      html  css  js  c++  java
  • 【WPF】MVVM前台绑定一组RadioButton按钮

    需求:制作一组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>
  • 相关阅读:
    React之Antd组件<Input />属性defaultValue问题记录。
    java多继承问题
    python多继承问题
    React之state
    概念题
    修复linux的yum源
    stl
    java
    python
    各种执行方式
  • 原文地址:https://www.cnblogs.com/guxin/p/wpf-mvvm-radio-button-on-itemscontrol.html
Copyright © 2011-2022 走看看