如何强制 TimeSpan 依赖于 enabled/disabled 按钮 WPF

How to force TimeSpan to be depended with enabled/disabled button WPF

我有一个 TimeSpan 文本框,我的目标是在 TIMESPAN 格式错误时禁用按钮保存 (exp 90:00:00)..

我尝试了一个代码,它只有一次是正确的..如果我设置 20:10:00 ..保存按钮被启用(正确)。 在那之后,TIMESPAN 是错误的 55:00:00,按钮被启用(数据库中的保存是 00:00:00)

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>

视图模型:

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;     

         }
    }

验证结果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");
    }
}

我怎样才能使它始终正常工作? 谢谢,

您不能将 TimeSpan 属性 设置为有效 TimeSpan 值以外的任何值,因此请在源 setter 中进行验证 属性 没有意义。

value 始终 是一个有效的时间跨度。

您应该在 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;
    }
}

如果此验证失败,TextBox 将出现红色边框(使用默认值 Validation.ErrorTemplate),表示该值无法转换为 TimeSpan 和 属性 不会被设置。