也许有读者不知道什么是二进制时钟我先解释下,就是把时间转换成二进制来显示,每一列就代表时间中的一个数字,从上往下为高位到低位,实现的思路为,把时间转换成二进制,然后装到二维数组里,每秒钟通过检查数组里的数值为0或者为1,来显示或隐藏控件,二维数组就对应画面上的24个小格子。
在项目中点右键,然后如下选择
并命名为BinaryClockControl.xaml
- public partial class BinaryClockControl : UserControl
- {
- DispatcherTimer timer = new DispatcherTimer();
- int[,] m_iBlockArray = new int[4, 6];
- public BinaryClockControl()
- {
- InitializeComponent();
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 1);
- timer.Tick += new EventHandler(timer_Tick);
- timer.Start();
- }
- void timer_Tick(object sender, EventArgs e)
- {
- // 根据时间设置数组的数值为0或者1
- try
- {
- DateTime dt = DateTime.Now;
- SetColFlag(0, dt.Hour / 10);
- SetColFlag(1, dt.Hour % 10);
- SetColFlag(2, dt.Minute / 10);
- SetColFlag(3, dt.Minute % 10);
- SetColFlag(4, dt.Second / 10);
- SetColFlag(5, dt.Second % 10);
- ControlVisibility();
- txtboxTime.Text = dt.ToString("HH:mm:ss");
- }
- catch (Exception ex) { MessageBox.Show(ex.Message); }
- }
- // 把数字转化为对应列的二进制
- private void SetColFlag(int columValue, int timeValue)
- {
- int rowValue = 3;
- while (timeValue > 0)
- {
- m_iBlockArray[rowValue--, columValue] = timeValue % 2;
- timeValue /= 2;
- }
- }
- private void ControlVisibility()
- {
- 控制控件的隐藏出现(省略的部分请参考书上附带的源码)
- }
- }
复制代码 其用法和CustomizedTextBox一样
如上图添加命名空间xmlns: my="clr-namespace:UIControlSets"
添加如下代码- <my:BinaryClockControl HorizontalAlignment="Center"/>
复制代码 如果用c#方式:- BinaryClockControl bcc = new BinaryClockControl();
- this.LayoutRoot.Children.Add(bcc);
-
复制代码
其实我们定义好的控件会自动出现在工具箱中当我们打开设计器就可以看到,我们可以像其它标准控件一样直接拖放到设计器上
|