Reputation: 469
I'm using a WPF ComboBox
whose IsEditable
value is set to true.
Basically, I have a list of items displayed in the ComboBox
. The user can type in a time if he does not find a suitable time in the ComboBox
.
I have attached a ValidationRule to my ComboBox.SelectedItem
so that whenever the user selects a time my ValidationClass is invoked (Derived from ValidationRule). All this works fine.
Since my ComboBox
is editable users can enter their own time. The validation class gets invoked everytime I type in a value int the ComboBox
and the value that gets passed to that class is the value I type in. Now the problem is, if the user types in a value that is not a part of the comobbox item the validation class gets invoked with a null value and thus im not able to validate anything.
Can anyone tell me how to validate the ComboBox.Text
item entered by the user?
My Validation class:
public class TimeValidateRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
TimeClass timeObj = value as TimeClass;
TimeSpan time;
if(timeObj == null)
return new ValidationResult(false, "Invalid Time");
if(timeObj.Time.Length < 5)
return new ValidationResult(false, "Invalid Time");
try
{
time = TimeSpan.Parse(timeObj.Time);
}
catch
{
return new ValidationResult(false, "Invalid Time");
}
// Get Current time (Arizona time)
if(!CheckAgainstArizonaTime(time))
return new ValidationResult(false, "Invalid Time");
return new ValidationResult(true, null);
}
}
ComboBox
declaration in xaml:
<ComboBox ItemsSource="{Binding Source={StaticResource TimeSelections}}"
ItemTemplate="{StaticResource TimeListTemplate}"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
Height="30" Width="100"
Name="cbTimes"
>
<ComboBox.SelectedItem>
<Binding
Path="SelectedTime"
UpdateSourceTrigger="PropertyChanged"
>
<Binding.ValidationRules>
<validators:TimeValidateRule/>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
Thanks, Jithu
Upvotes: 6
Views: 11407
Reputation: 543
<ComboBox Name="myComboBox">
<ComboBox.Text>
<Binding Path="SelectedTime" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validators:TimeValidateRule/>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
Upvotes: 2
Reputation: 8224
I know It's too late, but maybe this will help someone:
Bind to Text
property of ComboBox
, instead of SelectedItem
Upvotes: 8
Reputation: 7098
you need to handle the code and exceptions using event handler etc check on the net for further samples
Upvotes: 0