简体   繁体   中英

Datepicker ValidationRules from code behind: validation rule not called on user input

I'm creating a wpf UserControl that contains a Datepicker. This datepicker is generated from code behind in c#.

public partial class EditorDatePicker : UserControl
{
    public EditorDatePicker(TagEntry element, bool isTagPresent)
    {
        InitializeComponent();

        // datepicker binding and validation
        Binding binding = new Binding();

        binding.Path = new PropertyPath("DateDict[" + element.ParentTag + element.ChildTag + "]");
        binding.NotifyOnValidationError = true;
        binding.ValidatesOnDataErrors = true;
        binding.Converter = new DateTimeConverter();
        binding.Mode = BindingMode.TwoWay;
        binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        binding.ValidationRules.Add(new DateValidationRule());

        this.datePicker.SetBinding(DatePicker.SelectedDateProperty, binding);
    }


class DateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        if (value != null)
        {
            try
            {
                DateTime test = (DateTime)value;
                string date = test.ToString("d/M/yyyy");
                return (date);
            }
            catch
            {
                return null;
            }
        }
        return null;
    }

The fact is that the validation rule is never called when I manualy enter a date in the DatePicker text field (But it's called when using the datepicker). The only thing I got is a FormatException on lost focus.

Any idea? Thanx.

One possibility is to use converter:

public class DateTimeNullConverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider) => this;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
            return value.ToString();
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var text = value as string;
        DateTime result;
        if (text != null && DateTime.TryParse(text, out result))
            return result;
        return null;
    }
}

You can use it like this to bind to public DateTime? DateTime public DateTime? DateTime property:

<TextBox Text="{Binding DateTime, Converter={local:DateTimeNullConverter}}" />

ConvertBack will be called on lost focus.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM