我正在寻找一个时间选择器的解决方案,它允许我选择以下内容:
00:30 > 01:00 > 01:30
当它到达 23:30 时,需要回到 0:00。
换句话说,我需要通过选择向上或向下来增加半小时的周期。我已经尝试合并一个 hscroll
栏并修改一个 timepicker
但在我看来这是非常敏感和不必要的,因为我怀疑必须有更简单的方法吗?
任何建议都会很好。
最佳答案
我只是将 DomainUpDown
控件子类化来执行此操作,代码如下:
class TimePicker : DomainUpDown
{
public TimePicker()
{
// build the list of times, in reverse order because the up/down buttons go the other way
for (double time = 23.5; time >= 0; time -= 0.5)
{
int hour = (int)time; // cast to an int, we only get the whole number which is what we want
int minutes = (int)((time - hour) * 60); // subtract the hour from the time variable to get the remainder of the hour, then multiply by 60 as .5 * 60 = 30 and 0 * 60 = 0
this.Items.Add(hour.ToString("00") + ":" + minutes.ToString("00")); // format the hour and minutes to always have two digits and concatenate them together with the colon between them, then add to the Items collection
}
this.SelectedIndex = Items.IndexOf("09:00"); // select a default time
this.Wrap = true; // this enables the picker to go to the first or last item if it is at the end of the list (i.e. if the user gets to 23:30 it wraps back around to 00:00 and vice versa)
}
}
像这样将控件添加到您的表单中:
TimePicker picker1;
public Form1()
{
InitializeComponent();
picker1 = new TimePicker();
picker1.Name = "timePicker";
picker1.Location = new Point(10, 10);
Controls.Add(picker1);
}
然后当我们想要获取选择的时间时(我这里使用了一个按钮),我们只需使用SelectedItem
属性:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(picker1.SelectedItem.ToString()); // will show "09:00" when 09:00 is selected in the picker
}
DomainUpDown
的文档:http://msdn.microsoft.com/en-us/library/system.windows.forms.domainupdown.aspx
关于c# - 寻找半小时向上/向下的时间选择器控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16789399/