WPF 自定义计时器控件

最近要用到一个计时功能,所以临时写了一个控件,以备以后再次使用,不够完善,但功能算是实现了.效果图如下:

image

下面直接看如何实现吧:

步骤:

1.新建一个类 Timer.cs

public class Timer : Control
    {
        static Timer()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Timer), new FrameworkPropertyMetadata(typeof(Timer)));
        }
        public Timer()
        {
            timer.Interval = per;
            timer.Tick += Timer_Tick1;
        }
        private void Timer_Tick1(object sender, EventArgs e)
        {
            TimeSpan temp = DateTime.Now - StartTime - pauseTime;
            _text = string.Format("{0}:{1}:{2}", temp.Minutes, temp.Seconds, temp.Milliseconds);
        }
        private TimeSpan per = new TimeSpan(0, 0, 0, 0, 45);//时间间隔
        DispatcherTimer timer=new DispatcherTimer();//计时器
        public int status = 0;//0初始状态  1  进行状态  2 暂停状态
        public string _text
        {
            get { return (string)GetValue(_textProperty); }
            set { SetValue(_textProperty, value); }
        }
        /// <summary>
        /// 界面绑定用于显示时间
        /// </summary>
        public static readonly DependencyProperty _textProperty =
            DependencyProperty.Register("_text", typeof(string), typeof(Timer), new PropertyMetadata("0:0:0"));
        public static readonly RoutedEvent StatusChangedEvent = EventManager.RegisterRoutedEvent("StatusChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<int>), typeof(Timer));
        public event RoutedPropertyChangedEventHandler<int> StatusChanged
        {
            add { AddHandler(StatusChangedEvent, value); }
            remove { RemoveHandler(StatusChangedEvent, value); }
        }


        private TimeSpan pauseTime=TimeSpan.Zero;//从开始到现在期间暂停的时间
        private DateTime pauseStartTime;// 暂停 开始的时间


        private DateTime startTime;
        public DateTime StartTime
        {
            get { return startTime; }
            set { startTime = value;}
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Button csBtn = base.GetTemplateChild("ChangeStatusButton") as Button;
            if (csBtn != null)
            {
                csBtn.Click += ChangedStatusButton_Click;
            }
            Button stopBtn = base.GetTemplateChild("StopButton") as Button;
            if(stopBtn!=null)
            {
                stopBtn.Click += StopBtn_Click;
            }
        }
        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            int oldstatus = status;
            status = 0;
            timer.Stop();
            Button csBtn = base.GetTemplateChild("ChangeStatusButton") as Button;
            if (csBtn != null)
            {
                csBtn.Content = "开始";
            }
            RaiseStatusChangedEvent(oldstatus, status);
        }
        private void RaiseStatusChangedEvent(int oldvalue,int newvalue)
        {
            RoutedPropertyChangedEventArgs<int> args = new RoutedPropertyChangedEventArgs<int>(oldvalue, newvalue);
            args.RoutedEvent = StatusChangedEvent;
            this.RaiseEvent(args);
        }
        private void ChangedStatusButton_Click(object sender, RoutedEventArgs e)
        {
            Button csBtn = sender as Button;
            if (status == 0)
            {
                pauseTime = TimeSpan.Zero;
                _text = "0:0:0";
                int oldstatus = status;
                status = 1;
                startTime = DateTime.Now;
                timer.Start();
                csBtn.Content = "暂停";
                RaiseStatusChangedEvent(oldstatus, status);
            }
            else if (status == 1)
            {
                int oldstatus = status;
                status = 2;
                pauseStartTime = DateTime.Now;
                timer.Stop();
                csBtn.Content = "继续";
                RaiseStatusChangedEvent(oldstatus, status);
            }
            else  // if(status==2)//必然(继续)
            {
                int oldstatus = status;
                status = 1;
                pauseTime = pauseTime.Add(DateTime.Now - pauseStartTime);
                timer.Start();
                csBtn.Content = "暂停";
                RaiseStatusChangedEvent(oldstatus, status);
            }
        }
    }

在App.xaml内添加它的样式

<Style TargetType="{x:Type local:Timer}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:Timer}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Padding="0" Margin="0" Width="{TemplateBinding Width}"
                            Height="{TemplateBinding Height}"
                            CornerRadius="5">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="4*"></ColumnDefinition>
                                <ColumnDefinition Width="1.6*"></ColumnDefinition>
                                <ColumnDefinition Width="1.6*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock HorizontalAlignment="Left" Margin="10 0 0 0" VerticalAlignment="Center" Grid.Column="0" Text="{TemplateBinding _text}"></TextBlock>
                            <Button Name="ChangeStatusButton" Grid.Column="1" Width="40" Content="开始" Background="Transparent" HorizontalAlignment="Center" Margin="1" BorderThickness="0"></Button>
                            <Button Name="StopButton" Grid.Column="2" Content="结束" Background="Transparent" HorizontalAlignment="Center" Margin="1" BorderThickness="0">
                            </Button>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
</Style>

然后在MainWindow里面使用它:

image

好了,现在已经可以运行了.

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情

    暂无评论内容