繁体   English   中英

WPF Combobox验证

[英]WPF Combobox validation

我有一个带有性别的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}"/>

我决定这样做:

当用户单击“保存”时,将进行验证 然后,我只是检查验证事件,如果SelectedValue为null。 如果是这种情况,则意味着用户没有选择任何项目。 然后我警告他这个事实。

private void CanSave(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = myComboBox.SelectedValue != null;
}

Windows中的好方法是在组合框中添加一个值(None),并测试该人是否包含(None)值。 “(无)”是一个元选项,因为它不是选择的有效值 - 而是描述了选项本身未被使用。

正确: 替代文字
(来源: microsoft.com

不正确: 替代文字
(来源: microsoft.com

验证在您的情况下不起作用,因为当您想要说没有选择性别时,没有选择任何值...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM