【问题标题】:WPF Combobox validationWPF 组合框验证
【发布时间】:2009-07-28 08:44:30
【问题描述】:

我有一个带有性别的组合框(男,女..):我要求用户选择一个值(默认情况下,组合框没有值。)

<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;
            }
        }
}

问题是它从不输入 this[string columnname]。

当我尝试使用名称的 TextBox 时,它会输入 this[string columnname] 并且一切正常:

<TextBox  Style="{StaticResource textBoxInError}"   Text="{Binding Path=Surname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}"/>

【问题讨论】:

    标签: wpf validation combobox


    【解决方案1】:

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

    正确:
    (来源:microsoft.com

    不正确:
    (来源:microsoft.com

    验证不适用于您的情况,因为当您想说未选择性别时未选择任何值...

    【讨论】:

      【解决方案2】:

      我决定这样做:

      当用户点击保存时,验证发生。 然后我只需检查一个验证事件,如果 SelectedValue 为空。 如果是这种情况,则意味着用户没有选择任何项目。 然后我警告他这个事实。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多