I have a TimeSpan textbox, my objectif is to disable the button Save when the form of TIMESPAN is wrong (exp 90:00:00)..
I try a code, it is correct for just once time..if I set 20:10:00 ..The Save button is enabled (correct). After that however the TIMESPAN is wrong 55:00:00, the button is enabled ( and the saving in database is 00:00:00)
The XAML :
<TextBox Name="txtTime" Margin="10,10,10,10" >
<TextBox.Text >
<Binding Path="Time" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True" Mode="TwoWay" >
<Binding.ValidationRules>
<local:DateTimeValidationRule ValidationStep="RawProposedValue"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
The ViewModel :
public bool VarTIME ;
[Required(ErrorMessage = "Time is required")]
public TimeSpan Time
{
get { return time; }
set
{
time = value;
intervalString = Time.ToString();
TimeSpan reded;
bool success = TimeSpan.TryParseExact(intervalString, "hh\\:mm\\:ss",
CultureInfo.InvariantCulture, out reded);
if (success)
{
VarTIME = true;
}
OnPropertyChanged("Time");
}
}
public SheduleTrainViewModel()
{
VarTIME = false;
addTrain = new RelayCommand<string>(AddTrainFunction, canAddTrain);
private bool canAddTrain(string obj)
{ return VarTIME;
}
}
The VelidationResult class:
public class DateTimeValidationRule: ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string time;
Regex regex;
if (value == null)
return new ValidationResult(true, null);
else
time = value.ToString();
regex = new Regex(@"^([0-1]?\d|2[0-3])(?::([0-5]?\d))?(?::([0-5]?\d))?$");
if (regex.IsMatch(time.ToString()))
return new ValidationResult(true, null);
return new ValidationResult(false, "The time must match this format hh:mm:ss / hh:mm");
}
}
How I can fix it to be work always correct? Thanks,
You can't set a TimeSpan
property to anything else than a valid TimeSpan
value so doing the validation in the setter of the source property is meaningless.
value
is always a valid TimeSpan.
You should perform the validation in the ValidationRule
:
public class DateTimeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
TimeSpan reded;
if(!TimeSpan.TryParseExact(value.ToString(), "hh\\:mm\\:ss", CultureInfo.InvariantCulture, out reded))
return new ValidationResult(false, "Invalid time!");
return ValidationResult.ValidResult;
}
}
It this validation fails, the TextBox
will get a red border (using the default Validation.ErrorTemplate) that indicates that the value cannot be converted to a TimeSpan
and the property won't be set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.