仅绑定日期和时间

编程入门 行业动态 更新时间:2024-10-24 16:29:36
本文介绍了仅绑定日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有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>

更多推荐

仅绑定日期和时间

本文发布于:2023-11-27 08:37:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   日期   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!