美文网首页
[WPF] RadioButton绑定数据

[WPF] RadioButton绑定数据

作者: zhongwcool | 来源:发表于2020-08-06 17:29 被阅读0次

为建立中文知识库加块砖        ——中科大胡不归

0. 前言

终于用上了 RadioButton 了。

学习WPF: 第7个月。

1. View代码

<RadioButton IsChecked="{Binding LedSwitch,Mode=TwoWay,Converter={StaticResource RadioToBoolConverter},ConverterParameter=0}">打开</RadioButton>
<RadioButton IsChecked="{Binding LedSwitch,Mode=TwoWay,Converter={StaticResource RadioToBoolConverter},ConverterParameter=1}">关闭 </RadioButton>

2. Converter代码

public class Radio2BoolConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value != null && (value.ToString()?.Equals(parameter) ?? false);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value != null && value.Equals(true) ? parameter : Binding.DoNothing;
        }
    }

在 Convert 中,检查 value 的值是否和 parameter 的值一致,如果一致即为选中项,返回 true。界面上的效果即为选中。

在 ConvertBack 中,判断value的值为true的时候,会直接返回 parameter 的值,否则什么也不做Binding.DoNothing。

3. VM代码

        private int _ledSwitch = 1;

        public int LedSwitch
        {
            get => _ledSwitch;
            set
            {
                _ledSwitch = value;
                RaisePropertyChanged(nameof(LedSwitch));
            }
        }

4. 效果

参考文章:

  1. WPF中RadioButton绑定数据的正确方法
  2. wpf RadioButton按钮绑定数据过程
  3. WPF + MVVM + RadioButton:具有单个属性的句柄绑定

相关文章

  • [WPF] RadioButton绑定数据

    为建立中文知识库加块砖——中科大胡不归 0. 前言 终于用上了 RadioButton 了。 学习WPF: 第7个...

  • WPF数据绑定

    元素绑定 数据绑定最简单的形式是,源对象是WPF元素而且源属性是依赖属性。依赖项属性具有内置的更改通知支持,当在源...

  • WPF 数据绑定Binding

    自定义Binding 当为Binding设置了继承System.ComponentModel.INotifyPro...

  • WPF 数据绑定(一)

    最基本的绑定 将Text 的文本绑定到Window的Background属性,设置双向绑定,修改文本的值,改变Gr...

  • WPF 数据绑定(二)

    本例演示如何将数据模型的实例绑定到界面控件。 XAML代码如下:

    WPF 数据绑定(三)

    实现绑定一个对象的集合。在界面添加ListBox控件,指定显示对象的属性值。 在后台代码,获取数据集合源,绑定到L...

  • WPF 数据绑定(四)

    实现绑定到DataSet对象。 界面设计: 同样创建Grid的绑定,指定到列表元素,选择的Item

  • WPF 数据绑定(四)

    筛选的数据源的绑定,使用Linq Filter Data Collection。从数据集合中筛选符合设定条件的数据...

  • wpf 中的无效绑定

    设置wpf绑定的跟踪级别为high,output中观察wpf的处理流程: 对于一个无效的绑定,wpf尝试了5次,最...

  • WPF 数据绑定-绑定数据组集合

    UI设计: 列表绑定数据集合 后台代码: private ICollection products; produ...

网友评论

      本文标题:[WPF] RadioButton绑定数据

      本文链接:https://www.haomeiwen.com/subject/drqtdktx.html