在文本框中,“预期格式为DD / MM / YYYY”在WPF + MVVM +绑定+ UserInput中

时间:2018-09-12 05:29:51

标签: c# wpf-controls mvvm-light

我正在尝试在文本框中以指定格式输入有效日期。谁能帮助我确认在文本框中输入的日期是有效日期,并且其格式为DD / MM / YYYY?

如果用户输入的日期无效,则在按Tab键(在文本框外单击)后,应该说:日期输入错误。

查看模型:

私人DateTime? _txtDateDeRec;

    public DateTime? TxtDateDeRec
    {
        get
        {
            return this._txtDateDeRec;
        }
        set
        {
            this._txtDateDeRec = value;
            OnPropertyChanged("TxtDateDeRec");
        }
    }

XAML代码是:

TextBox x:Name =“ txtDateDeRec” Horizo​​ntalAlignment =“ Left” Height =“ 23” Margin =“ 555,65,0,0” TextWrapping =“ Wrap” Text =“ {Binding TxtDateDeRec}” VerticalAlignment =“ Top”宽度=“ 163”

2 个答案:

答案 0 :(得分:0)

        textBox1.Leave += new EventHandler((sender2, ee) => 
        {
            var textBox = (Control)sender2;
            var date = new DateTime();
            if(DateTime.TryParse(textBox.Text,out date))
            {
                textBox.Text= String.Format("{0:dd/MM/yyyy}", date);
            }
            else
            {
                textBox.Text = "date wrongly entered.";
            }

        });

更新1:仅格式DD / MM / YYY

textBox1.Leave += new EventHandler((sender2, ee) => 
            {
                var textBox = (Control)sender2;
                var date = new DateTime();
                var testResult = DateTime.TryParse(textBox.Text, out date);
                var dateToString = String.Format("{0:dd/MM/yyyy}", date);
                if(testResult==true && textBox.Text.Trim() == dateToString)//Format is the same
                {

                    textBox.Text =dateToString ;
                }

                else
                {
                    textBox.Text = "date wrongly entered.";
                }

            });

答案 1 :(得分:0)

要验证日期时间格式,可以在文本框上的绑定中使用“验证规则”。

public class DateValidation : ValidationRule 
    { 
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
        { 
            ValidationResult result; 
            try 
            { 
               Regex regex = new Regex(@"^([0]?[0-9]|[12][0-9]|[3][01])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$");

               DateTime? date;

               //Verify whether date entered in dd/mm/yyyy format.
               bool isValid = regex.IsMatch(value.ToString());

               //Verify whether entered date is Valid date.       
               isValid = isValid && DateTime.TryParseExact(value.ToString(), "dd/MM/yyyy", new CultureInfo("en-GB"), DateTimeStyles.None, out date);                                                                                                             

               result = isValid ? new ValidationResult(true,null) : new ValidationResult(false,"Date wrongly entered");  
            }catch(Exception ) 
            { 
                result = new ValidationResult(false,"Date wrongly entered"); 
            } 
            return result; 
        } 
    } 

对于文本框,如下所示添加验证规则

<TextBox  x:Name="txtDateDeRec" HorizontalAlignment="Left" Height="23" Margin="555,65,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="163">
    <TextBox.Text>
        <Binding Path="TxtDateDeRec" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:DateValidation/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>