Reputation: 12293
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}"/>
Upvotes: 4
Views: 10139
Reputation: 475
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:
(source: microsoft.com)
Incorrect:
(source: microsoft.com)
The validation doesn't work in your case because no value is selected when you want to say that no sex is selected...
Upvotes: 1
Reputation: 12293
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;
}
Upvotes: 0