c# – 仅限绑定日期和仅限时间

我有2个控件:

DatePicker:仅适用于日期
带有TimeMask的TextBox:仅限时间

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

我理解它的原因,但是最好的解决方案是让它们分开工作但是绑定到同一个属性?

我试图占用当前时间并在set属性中构建一个新的Date但总是出现溢出错误.

解决方法:

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

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;
    }
}

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

<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>
上一篇:android – 更改DatePicker标题文本颜色


下一篇:javascript – 在材料ui的datepicker中更改formatDate