仅绑定日期和时间 [英] Binding Date Only and Time Only

查看:98
本文介绍了仅绑定日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个控件:

I have 2 controls:

DatePicker:仅限日期

带TimeMask的文本框:仅适用于

DatePicker: For Date Only
TextBox with TimeMask: For Time Only

它们都链接到相同的属性 DateTime EffectiveDate
但是问题是当我更改DatePicker上的Date时,它将TimeTextBox中的Time改为12:00。

They are both linked to the same property DateTime EffectiveDate But the problem is when I change the Date on the DatePicker, it changes the Time in the TimeTextBox back to 12:00.

我了解原因,但是最好的解决方案是让这些工作分开但是绑定到同一个财产?

I understand the reason for it, but what best solution is out there to let these work separately but bound to the same property?

我已经尝试使用当前时间并在set属性中构建一个新的Date,但总是会出现溢出错误。

I have tried to take the current time and build a new Date in the set property but always end up with overflow errors.

推荐答案

您可以使用值转换器来保持值

You can use a value converter to hold on to the value

public class DateConverter : IValueConverter
{
    private DateTime timePickerDate;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        timePickerDate = ((DateTime)(value));

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return timePickerDate;

        var datePickerDate = ((DateTime)(value));

        // compare relevant parts manually
        if (datePickerDate.Hour != timePickerDate.Hour
            || datePickerDate.Minute != timePickerDate.Minute
            || datePickerDate.Second != timePickerDate.Second)
        {
            // correct the date picker value
            var result = new DateTime(datePickerDate.Year,
                 datePickerDate.Month,
                 datePickerDate.Day,
                 timePickerDate.Hour,
                 timePickerDate.Minute,
                 timePickerDate.Second);

            // return, because this event handler will be executed a second time
            return result;
        }

        return datePickerDate;
    }
}

并将有问题的两个控件绑定到一个属性,但日期选择器使用转换器不覆盖时间。

And have the two controls in question bind to the one property but have the date picker use the converter to not override the time.

<Grid Margin="10,5" >        
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <sdk:DatePicker Grid.Column="0" TabIndex="1" Padding="0" SelectedDate="{Binding EffectiveDate, Mode=TwoWay, Converter={StaticResource DateConverter}}" SelectedDateFormat="Short"/>
    <toolkit:TimePicker Grid.Column="1" Value="{Binding EffectiveDate, Mode=TwoWay}" Margin="0" Padding="0" HorizontalAlignment="Left" TabIndex="2" />
</Grid>

这篇关于仅绑定日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆