When I type something in the Combobox, I want the validation check to occur and display the validation error. That doesn't seem to be happening with this code. How do I get the validation check to happen and validation error to show, when I pick a value from the combobox list or type a value in combobox?
<ComboBox x:Name="Cbx2"
IsEditable="True"
Grid.Row="5" Grid.Column="2"
HorizontalAlignment="Stretch"
ItemsSource="{Binding ValuesList, Mode=OneWay}"
SelectedValue="{Binding SelectedCbxValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
SelectionChanged="OnSelectionChanged"
LostFocus="TxtBox_LostFocus">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SelectedCbxValue, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ComboBox>
Viewmodel
public class SOViewModel : ViewModelBase, IDataErrorInfo
{
private ObservableCollection<string> _valuesList;
public ObservableCollection<string> ValuesList
{
get => _valuesList;
set => SetProperty(ref _valuesList, value);
}
private bool _isValid;
public bool IsValid { get => _isValid; set => SetProperty(ref _isValid, value); }
private string _selectedCbxValue;
public string SelectedCbxValue { get => _selectedCbxValue; set => SetProperty(ref _selectedCbxValue, value); }
#region IDataErrorInfo properties
private string _error;
public string Error { get => _error; set => SetProperty(ref _error, value); }
public string this[string propName]
{
get
{
return ValidateProperty(propName);
}
}
private string ValidateProperty(string propName)
{
string errorMessaage = string.Empty;
bool ValidateValue(string valueToValid)
{
// validation code goes here
return true;
}
if (propName == nameof(SelectedCbxValue))
{
IsValid = IsValid && ValidateValue(SelectedCbxValue);
}
if (string.IsNullOrEmpty(errorMessaage)) { Error = null; }
else { Error = errorMessaage; }
return errorMessaage;
}
#endregion
}
Google led me here and it was helpful: WPF Editable ComboBox validation