WPF组合框验证

4
我有一个包含性别选项(男,女...)的ComboBox:要求用户选择一个值(ComboBox默认没有值)。
<ComboBox ItemsSource="{x:Static Member=data:Sex.AllTypes}" SelectedItem="{Binding Path=Sex.Value, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}"  VerticalAlignment="Top">
        <ComboBox.ItemTemplate>
             <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                      <TextBlock Text="{Binding Path=Name}" />
                  </StackPanel>
             </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

Sex.Value是我Person类中的一个属性:

public class Person : IDataErrorInfo 
{
public string this[string columnName]
        {
            get
            {                
                switch (columnName)
                {                   
                    case "Sex": return Sex.Value == null ? "Required field" : null;
                    case "Surname": return string.IsNullOrEmpty(Nachname) ? "Required field" : null;
                }                
            }
        }
 public string Error
        {
            get
            {
                return null;
            }
        }
}

问题在于它从未进入此[string columnname]。当我尝试使用名称为TextBox的文本框时,它会进入此[string columnname],一切正常工作。
<TextBox  Style="{StaticResource textBoxInError}"   Text="{Binding Path=Surname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}"/>
2个回答

1
在Windows中的良好做法是将一个值(None)添加到组合框中,并测试人员是否包含(None)值。"(None)" 是元选项,因为它不是选择的有效值,而是描述该选项本身未被使用。
正确: alt text
(来源:microsoft.com) 不正确: alt text
(来源:microsoft.com) 在您想要表示未选择性别时,验证无法工作,因为没有选择任何值......

0
我决定这样做:
当用户点击保存时,进行验证。 然后在验证事件中简单地检查SelectedValue是否为空。 如果是这种情况,则意味着用户没有选择任何项目。 然后我会提醒他这个事实。
private void CanSave(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = myComboBox.SelectedValue != null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接