未选择任何选项时的RadioButton ValidationRule

时间:2015-11-05 16:20:50

标签: c# wpf validation radio-button

我试图找出如何为radiobutton创建验证规则。我想要实现的是用户必须通过无线电按钮选择一个选项。

我的ViewModel有一个基于Enum的属性:

public enum Gender
{
    Unknown,
    Male,
    Female
}

[ImplementPropertyChanged]
public class MyViewModel
{
    public Gender Gender { get; set; }

    public MyViewModel()
    {
        Gender = Gender.Unknown;
    }
}

<StackPanel Orientation="Horizontal">
    <RadioButton Content="Male" IsChecked="{Binding Gender, ConverterParameter={x:Static data:Gender.Male}, Converter={StaticResource EnumToBooleanConverter}}"/>
    <RadioButton Content="Female" IsChecked="{Binding Gender, ConverterParameter={x:Static data:Gender.Female}, Converter={StaticResource EnumToBooleanConverter}}"/>
</StackPanel>

我有一个&#39;错误&#39;复选框的样式(红色边框,字体颜色等)

Gender仍设置为Unknown时,如何为每个单选按钮触发ValidationRule,我该如何实现? (所以都显示我的错误风格)

1 个答案:

答案 0 :(得分:0)

我已经开始工作,而不是使用ValidationRule但使用IDataErrorInfo

[ImplementPropertyChanged]
public class MyViewModel : IDataErrorInfo
{
    public Gender Gender { get; set; }

    public MyViewModel()
    {
        Gender = Gender.Unknown;
    }

    public string this[string name]
    {
        get
        {
            if (name == "Gender" && Gender == Gender.Unknown)
            {
                return "Gender need to be known";
            }
            return null;
        }
    }

    public string Error
    {
        get
        {
            return null;
        }
    }
}

<StackPanel Orientation="Horizontal">
    <RadioButton Content="Male" IsChecked="{Binding Gender, ConverterParameter={x:Static data:Gender.Male}, Converter={StaticResource EnumToBooleanConverter}, NotifyOnSourceUpdated=True, ValidatesOnDataErrors=True}"/>
    <RadioButton Content="Female" IsChecked="{Binding Gender, ConverterParameter={x:Static data:Gender.Female}, Converter={StaticResource EnumToBooleanConverter}, NotifyOnSourceUpdated=True, ValidatesOnDataErrors=True}"/>
</StackPanel>

<强>要点:

  • 在代码工具IDataErrorInfo
  • 在xaml中将NotifyOnSourceUpdated=True, ValidatesOnDataErrors=True添加到RadioButtons