c# - 寻找半小时向上/向下的时间选择器控制

标签 c# .net winforms

我正在寻找一个时间选择器的解决方案,它允许我选择以下内容:

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/

相关文章:

c# - 如何将RadDataForm设置为插入模式?

c# - 使用最大化窗口时如何更改标签的位置

c# - 在 C# 中处理共享 dll 的最佳方法是什么?

c# - 将 app.config 配置部分重新定位到 AppData 文件夹

.net - .net 中的读取锁

c# - 从任务计划程序运行时,Windows 服务器上的预定 C# 控制台应用程序不显示控制台

.net - WCF中有没有办法在发生异常时处理HTTP响应?

c# - CS0122 Form1.AvgWaiting 由于其保护级别和 C# Windows 窗体中的甘特图而无法访问

.net - .net 中没有间隙的柱形图

c# - 如何在 TabPages/TabControl 中滚动