WPF Combobox validation

I have a ComboBox with Sex (male, female ..): And I require the user to select a value (by default, the ComboBox does not matter.)

<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 of the 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 goes into this [string columnname].

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

 <TextBox Style="{StaticResource textBoxInError}" Text="{Binding Path=Surname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}"/> 
+4
source share
2 answers

A good way on Windows is to add the value (No) to the combo box and check if the person contains the value (No). "(No)" is a meta option because it is not a valid value for selection - rather, it describes that the option itself is not used.

Right: alt text
(source: microsoft.com )

Wrong: alt text
(source: microsoft.com )

The check does not work in your case, because the value is not selected, if you want to say that the gender is not selected ...

0
source

I decided to do it as follows:

When the user clicks the "Save" button, a check appears. Then I just check the validation event if SelectedValue is null. If so, this means that the user has not selected any of the items. Then I warn him about this fact.

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

All Articles