【发布时间】:2009-09-09 08:48:36
【问题描述】:
我正在使用 WPF ComboBox,其 IsEditable 值设置为 true。
基本上,我有一个显示在ComboBox 中的项目列表。如果在ComboBox 中没有找到合适的时间,用户可以输入时间。
我已将 ValidationRule 附加到我的 ComboBox.SelectedItem 以便每当用户选择调用我的 ValidationClass 的时间(派生自 ValidationRule)。这一切都很好。
由于我的ComboBox 是可编辑的,用户可以输入自己的时间。每次我在ComboBox 中输入一个值时都会调用验证类,传递给该类的值就是我输入的值。现在的问题是,如果用户输入的值不是comobbox 项,验证类使用空值调用,因此我无法验证任何内容。
谁能告诉我如何验证用户输入的ComboBox.Text 项?
我的验证类:
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 在 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>
谢谢, 吉图
【问题讨论】:
标签: wpf validation combobox