未选择任何选项时的单选按钮验证规则
本文关键字:单选按钮 验证 规则 选择 任何 选项 | 更新日期: 2023-09-27 18:20:47
我正试图找出如何为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>
我有一个复选框的"错误"样式(红色边框、字体颜色等)
当Gender
仍然设置为Unknown
时,我应该如何实现为每个单选按钮触发ValidationRule?(所以都显示了我的错误风格)
我已经让它工作了,不是用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