首页 > 其他分享 >WPF绑定Enum到RadioButton

WPF绑定Enum到RadioButton

时间:2023-08-21 10:46:08浏览次数:36  
标签:Gender Enum value RadioButton bool new WPF parameter throw

将枚举型的数据类型绑定到单选按钮的IsChecked属性中,可以避免定义多个bool类型与之进行绑定,尤其是枚举类型较多时候,对bool对象的维护会更加复杂。

1、定义枚举类型及值转换器

internal enum Gender
{
    [Description("男")] Male,
    [Description("女")] Female,
    [Description("未知")] Unknown
}
[ValueConversion(typeof(Gender), typeof(bool?))]
public class Gender2IsCheckedConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool?))
        {
            throw new InvalidOperationException("The target must be a bool");
        }

        if (value == null || parameter == null)
        {
            throw new ArgumentNullException();
        }

        if (!Enum.IsDefined(typeof(Gender), value))
        {
            throw new InvalidOperationException("The value must be a Gender");
        }

        if (!Enum.IsDefined(typeof(Gender), parameter))
        {
            throw new InvalidOperationException("The parameter must be a Gender");
        }

        return (Gender)value == (Gender)parameter;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(Gender))
        {
            throw new InvalidOperationException("The target must be a Gender");
        }

        if (parameter == null || !Enum.IsDefined(typeof(Gender), parameter))
        {
            throw new InvalidOperationException("The parameter must be a Gender");
        }

        if (value is not bool isChecked)
        {
            throw new InvalidOperationException("The value must be a bool");
        }

        return isChecked ? (Gender)parameter : Binding.DoNothing;
    }
}

2、定义RadioButton控件,并进行绑定

<Window x:Class="WpfDeveloping.Views.RadioSampleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:valueConverters="clr-namespace:WpfDeveloping.ValueConverters"
        xmlns:models="clr-namespace:WpfDeveloping.Models"
        mc:Ignorable="d"
        Title="RadioSampleWindow"
        WindowStartupLocation="CenterScreen"
        Height="180" Width="320">
    <Window.Resources>
        <valueConverters:Gender2IsCheckedConverter x:Key="GenderConverter"/>
        <Style x:Key="MyRadioButton" TargetType="RadioButton">
            <Setter Property="Height" Value="30"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Margin" Value="10,0,0,0"/>
        </Style>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <RadioButton Content="男" Style="{StaticResource MyRadioButton}"
                     IsChecked="{Binding Gender, Converter={StaticResource GenderConverter}, ConverterParameter={x:Static models:Gender.Male}}"/>
        <RadioButton Content="女" Style="{StaticResource MyRadioButton}"
                     IsChecked="{Binding Gender, Converter={StaticResource GenderConverter}, ConverterParameter={x:Static models:Gender.Female}}"/>
        <RadioButton Content="未知" Style="{StaticResource MyRadioButton}"
                     IsChecked="{Binding Gender, Converter={StaticResource GenderConverter}, ConverterParameter={x:Static models:Gender.Unknown}}"/>
    </StackPanel>
</Window>

3、在ViewModel中定义枚举对象

internal class RadioSampleWindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public Gender Gender
    {
        get => _gender;
        set
        {
            if (_gender != value)
            {
                _gender = value;
                OnPropertyChanged();
                Debug.WriteLine($"Current gender: {value}");
            }
        }
    }

    private Gender _gender = Gender.Unknown;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

4、运行截图

标签:Gender,Enum,value,RadioButton,bool,new,WPF,parameter,throw
From: https://www.cnblogs.com/xhubobo/p/17645373.html

相关文章

  • 【愚公系列】2023年08月 WPF控件专题 CheckBox控件详解
    (文章目录)前言WPF控件是WindowsPresentationFoundation(WPF)中的基本用户界面元素。它们是可视化对象,可以用来创建各种用户界面。WPF控件可以分为两类:原生控件和自定义控件。原生控件是由Microsoft提供的内置控件,如Button、TextBox、Label、ComboBox等。这些控件都是WPF中常见......
  • qt之QRadioButton中选中和未被选中的两种状态使用
    点击按钮,选择转到槽的时候,选择cliked(bool)选项 以下是代码部分关于两种状态的使用1voidWidget::on_radioButton_clicked(boolchecked)2{3if(checked==0){4qDebug()<<4/qRound(1.4999999);5qDebug()<<"000";6}elseif(checked==......
  • 【愚公系列】2023年08月 WPF控件专题 Button控件详解
    (文章目录)前言WPF控件是WindowsPresentationFoundation(WPF)中的基本用户界面元素。它们是可视化对象,可以用来创建各种用户界面。WPF控件可以分为两类:原生控件和自定义控件。原生控件是由Microsoft提供的内置控件,如Button、TextBox、Label、ComboBox等。这些控件都是WPF中常见......
  • WPF 转换器Converter 多值处理
    定义多值处理方法。usingSystem;usingSystem.Globalization;usingSystem.Windows.Data;namespacedemo_business.Converters{publicclassNumIntervalConverter:IMultiValueConverter{publicobjectConvert(object[]values,TypetargetType,objectparameter......
  • WPF初始化顺序
    WPF的初始化的顺序///<summary>///MainWindow.xaml的交互逻辑///</summary>publicpartialclassMainWindow:Window{publicMainWindow(){InitializeComponent();}privatevoidWindow_A......
  • 题解:【CF858E】 Tests Renumeration
    题目链接一点模拟下下火。首先一定不能覆盖的,只能一点一点挪。将已经在合法位置上的去掉,剩下的测试分为四类:不碍事的样例测试。不碍事的常规测试。占据了样例测试位置的常规测试。占据了常规测试位置的样例测试。将\(1\simn\)中还未使用的空闲位置记录下来,结论是只需......
  • WPF加载GIF的五种方式(Storyboard / WpfAnimatedGif / ImageAnimator / PictureBox / M
    部分内容参考博文WPF如何显示gif一、使用Storyboard效果:  (1)页面xaml:<Windowx:Class="PlayGifDemo.StoryboardWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2......
  • wpf 自定义轮播图组件
      轮播图组件代码:[Localizability(LocalizationCategory.None,Readability=Readability.Unreadable)][TemplatePart(Name="Part_Grid",Type=typeof(Grid))][TemplatePart(Name="Part_OldContentControl",Type=typeof(ContentControl))][Template......
  • WPF ListBox 控件绑定 Binding
     当我们需要用到循环的列表内容,并且模板化程度高的时候,建议使用 ListBox 来做绑定。XAML:<Window.DataContext><local:VMTempTest/></Window.DataContext><StackPanelMargin="10,0,0,50"Orientation="Vertical"><TextBlockText="ListBo......
  • WebView2在WPF中的应用
    开发环境运行环境:.Net6开发环境:VisualStudio202217.1.3框架语言:WPF安装WebView2通过PackageManager控制台安装Install-PackageMicrosoft.Web.WebView2通过Nuget包管理器安装在窗体中添加名字空间:xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;asse......