WPF Combobox validation

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have a ComboBox with Sex(male, female..):And I demand from user to select a value (the ComboBox has no value by default.)

<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 is a Property in my Person class:

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

the problem is that it never enters this[string columnname].

When i try a TextBox with name, it enters this[string columnname] and everything works fine:

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

回答1:

The good way in windows is to add a value (None) into the combobox and test if the person contains the (None) value. "(None)" is a meta-option because it is not a valid value for the choice―rather it describes that the option itself isn't being used.

Correct: alt text http://i.msdn.microsoft.com/Aa511458.DropDownLists41(en-us,MSDN.10).png

Incorrect: alt text http://i.msdn.microsoft.com/Aa511458.DropDownLists40(en-us,MSDN.10).png

The validation doesn't work in your case because no value is selected when you want to say that no sex is selected...



回答2:

I've decided to do it this way:

When user clicks on Save, the validation occur. Then I simply check in a validation event, if a SelectedValue is null. If it's the case, then it means that the user didn't choose any of items. Then I warn him about this fact.

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!