验证 WPF 组合框中的选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16923922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:55:39  来源:igfitidea点击:

Validate the selected value in a WPF combobox

c#wpf

提问by Jesus Zamora

Like the title says, I am trying to validate my form, but I have an issue getting the combobox value:

正如标题所说,我正在尝试验证我的表单,但在获取组合框值时遇到了问题:

<ComboBox Name="ComboBox_Country" 
          Validation.Error="Validation_Error"
          Text="{Binding UpdateSourceTrigger=PropertyChanged, 
                         Path=Form_Country,
                         ValidatesOnDataErrors=true,
                         NotifyOnValidationError=true}"/>

Which is then validated with my class FormValidation like so:

然后使用我的类 FormValidation 进行验证,如下所示:

            public string this[string columnName]
            {
               get
            {
               string result = null;

               if (columnName == "Form_Country")
               {
                  if (string.IsNullOrEmpty(Form_Country) || !verifyNumericValue(Form_Country))
                    result = "Please choose a correct option.";
               }

            }

I use these functions to call the validation in my form.

我使用这些函数在我的表单中调用验证。

    private void Confirm_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = _errors == 0;
        e.Handled = true;
    }

    private void Confirm_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        _generic = new UnidadValidation();
        grid_UnidadData.DataContext = _generic;
        e.Handled = true;
    }

    private void Validation_Error(object sender, ValidationErrorEventArgs e)
    {
        if (e.Action == ValidationErrorEventAction.Added)
            _errors++;
        else
            _errors--;
    }

I wish to get the selected value, not the selected text. What is my best option?

我希望获得选定的值,而不是选定的文本。我最好的选择是什么?

回答by Jesus Zamora

Stupid, stupid stupid lack of observation on my part. If you were to change the ComboBox's Textto SelectedValueinstead like so:

愚蠢,愚蠢的愚蠢缺乏对我的观察。如果你要改变组合框的TextSelectedValue,而不是像这样:

<ComboBox Name="ComboBox_Pais" 
          Validation.Error="Validation_Error"
          SelectedValue="{Binding UpdateSourceTrigger=PropertyChanged, 
                                  Path=Escuela_Pais,
                                  ValidatesOnDataErrors=true, 
                                  NotifyOnValidationError=true}"/>

One will get the selected value and NOT the text.

一个将获得选定的值而不是文本。

For those of you who might want to read on it, I found the original tutorial here.

对于那些可能想阅读它的人,我在这里找到了原始教程。

WPF TextBox Validation with IDataErrorInfo

使用 IDataErrorInfo 验证 WPF 文本框