如何取消选中 WPF (MVVM) 中的单选按钮 [英] How to Uncheck radio button in WPF (MVVM)

查看:66
本文介绍了如何取消选中 WPF (MVVM) 中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单选按钮组.选择不是填写表格的强制性要求.开始时,所有单选按钮都未选中.如果用户无意中点击了其中之一,他将无法返回,因为必须至少检查一个.

I have a radio buttons group. The choice is not mandatory to fill the form. At the beginning all the radio buttons are unchecked. If the user unintentionally clicks on one of them, he can not go back, because at least one has to be checked.

那么如何取消选中单选按钮而不强迫用户做出不需要的选择?

So How can I uncheck a radio button and not force the user to make an unwanted choice?

附言该表单是在运行时构建的,我遵循 MVVM 设计模式.对于强制选项,单选按钮解决方案非常适合,我已经在这种情况下使用它.

p.s. the form is built at run-time and I am following the MVVM design pattern. For Mandatory choices, the radio buttons solution fit very well and I already use it in this case.

推荐答案

就我个人而言,当我想要这种行为时,我使用 ListBox 并覆盖模板以使用 RadioButtons.

Personally when I want this behavior I use a ListBox with the Template overwritten to use RadioButtons.

这是最适合执行以下所有操作的控件:

It's the best control suited to do all of the following :

  • 显示项目列表
  • 一次只能选择一项,因此数据模型中只维护一个属性
  • 用户可以将选中的项目保留为空,表示未选中任何项目

我的 ListBox 自定义样式删除了边框和背景颜色,并使用 RadioButton 绘制每个项目,其中 IsChecked 绑定到ListBoxItem.IsSelected.通常是这样的:

My custom style for the ListBox removes the borders and background color, and draws each item using a RadioButton with the IsChecked bound to the ListBoxItem.IsSelected. Typically something like this :

<Style x:Key="RadioButtonListBoxStyle" TargetType="{x:Type ListBox}">
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle" />
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="{x:Type ListBoxItem}" >
                <Setter Property="Margin" Value="2, 2, 2, 0" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Border Background="Transparent">
                                <RadioButton
                                    Content="{TemplateBinding ContentPresenter.Content}" VerticalAlignment="Center"
                                    IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

并且显示 RadioButtons 本身通常非常简单,如下所示:

And to display the RadioButtons themselves is usually something very simple, like this :

<ListBox ItemsSource="{Binding AvailableValues}"
         SelectedValue="{Binding SelectedValue}"
         Style="{StaticResource RadioButtonListBoxStyle}" />

这篇关于如何取消选中 WPF (MVVM) 中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆