我正在寻找时间选择器的解决方案,它允许我选择以下内容:
00:30 > 01:00 > 01:30
Run Code Online (Sandbox Code Playgroud)
当它到达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)
}
}
Run Code Online (Sandbox Code Playgroud)
将控件添加到表单中,如下所示:
TimePicker picker1;
public Form1()
{
InitializeComponent();
picker1 = new TimePicker();
picker1.Name = "timePicker";
picker1.Location = new Point(10, 10);
Controls.Add(picker1);
}
Run Code Online (Sandbox Code Playgroud)
然后当我们想要获得所选时间时(我在这里使用一个按钮),我们只需使用该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
}
Run Code Online (Sandbox Code Playgroud)
文档DomainUpDown:http://msdn.microsoft.com/en-us/library/system.windows.forms.domainupdown.aspx
| 归档时间: |
|
| 查看次数: |
1909 次 |
| 最近记录: |