Best way to manage 2 pairs of DateTimePickers (From and To)?
对DateTimePickers感到很沮丧...首先,让我解释一下我的设置。我有2对DateTimePickers。 1是"起始日期"(格式为MM / dd / yyyy),其对是"起始时间"(格式为HH和ShowUpDown = true)。另一对是相同的,除了其" To Date"和" To Hour"。他们需要遵守一些规则。
我肯定还有更多,但我已经筋疲力尽了……我想大家都明白。我试图通过一些棘手的DataBindings来完成此任务,例如:
在构造方法中:
1 2 3 4 5 6 7 8 9 10 11 12 | FromDatePicker.DataBindings.Add(new Binding("MaxDate", ToHourPicker,"MaxDate")); ToDatePicker.DataBindings.Add(new Binding("MaxDate", ToHourPicker,"MaxDate")); FromHourPicker.DataBindings.Add(new Binding("Value", FromDatePicker,"Value")); ToHourPicker.DataBindings.Add(new Binding("Value", ToDatePicker,"Value")); DateTime dt = DateTime.Now.Subtract(new Timespan(0, 0, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond)); DateTime plusOne = dt.AddHours(1); FromDatePicker.MaxDate = dt; FromHourPicker.MaxDate = dt; ToDatePicker.MaxDate = plusOne; ToHourPicker.MaxDate = plusOne; |
在MainForm加载事件中
1 2 3 4 | FromDatePicker.Value = FromDatePicker.MaxDate; FromHourPicker.Value = FromDatePicker.MaxDate; ToDatePicker.Value = ToDatePicker.MaxDate; ToHourPicker.Value = ToHourPicker.MaxDate; |
使用该设置,它实际上在
我非常困惑并且乐于提高自己的水平,或者如果你们可以想到一种更简单的方法来达到同样的效果,我显然也很想听听那些建议:P。让我知道您是否需要更多
所以我通过eXtreme DataBinding实现了我想要的东西。哈哈...看起来不错,但是可以用!
首先,我在表单中创建了一个称为MasterMaxDate的属性,该属性将始终为问题陈述中所述的Now 1 hour。
1 | public DateTime MasterMaxDate { get; set; } |
然后,我将ToDate选择器对的MaxDate属性绑定到MasterMaxDate:
1 2 |
接下来,我将FromDate选择器对的MaxDate属性绑定到ToHour选择器的Value属性(因为ToHour选择器最准确)。这样可以确保FromDate永远不会> ToDate。
1 2 |
接下来,(现在是奇怪的部分),我必须将一对值中的每个选择器绑定到另一个,以确保它们始终保持同步:
1 2 3 4 5 | FromDatePicker.DataBindings.Add(new Binding("Value", FromHourPicker,"Value")); FromHourPicker.DataBindings.Add(new Binding("Value", FromDatePicker,"Value")); ToDatePicker.DataBindings.Add(new Binding("Value", ToHourPicker,"Value")); ToHourPicker.DataBindings.Add(new Binding("Value", ToDatePicker,"Value")); |
最后,设置MasterMaxDate:
1 2 3 4 | DateTime now = DateTime.Now; DateTime dt = DateTime.Now.Subtract(new TimeSpan(0, 0, now.Minute, now.Second, now.Millisecond)); MasterMaxDate = dt.AddHours(1); |
它有效!所有更新均实时存在并保持同步! (例如:如果我将ToDate选择器更改为FromDate选择器之前的日期,FromDate选择器也会自动更改,以保持在ToDate选择器"之后"。)
现在回头看一下,让配对中的每个选择器"共享"一个ValueChanged事件并以这种方式进行处理可能会更容易,但是我很高兴我能够做到这一点。
更新
我必须为MasterMaxDate实现INotifyPropertyChanged,以便它将其新值报告给DateTimePickers。在此示例中使用接受的答案
DateTime dt = DateTime.Now.Subtract(new Timespan(0, 0, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond));
1 2 | DateTime now = DateTime.Now; DateTime dt = now.Subtract(new Timespan(0, 0, now.Minute, now.Second, now.Millisecond)); |
接下来,忘记所有这些废话,并使用
1 2 | DateTime dt = now.Date; // time component is set to 00:00:00 DateTime plusOne = now.AddHours(1); |
With that setup it actually fails on the FromDatePicker.Value = FromDatePicker.MaxDate; line with the error message of Value of is not valid. Value should be between MinDate and MaxDate,
这可能会解决问题