c# wpf 应用程序中的时钟 [英] a clock in c# wpf application

查看:31
本文介绍了c# wpf 应用程序中的时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在开发 c# wpf 应用程序,我想为我的应用程序添加一个时钟:
  • 如何在我的应用程序中制作时钟?
  • 如何让我的应用程序时钟不链接到 Windows 时钟??
  • 如何在我的应用程序中以不同的样式显示时钟?
  • 如何使其包含日历、时区...等并通过我的应用程序本身修改这些内容?
  • 我可以将数据库中的时间戳链接到应用程序时钟吗?如何实现?

推荐答案

制作这样的时钟会很容易.

It would be quite easy to make a clock like this.

这是一个让你入门的小例子

Here is a small example to get you started

XML:

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="233" Width="143" Name="UI">
    <Grid DataContext="{Binding ElementName=UI}">
        <StackPanel>
            <TextBlock Text="{Binding CurrentTime}" />
            <ComboBox ItemsSource="{Binding TimeZones}" SelectedItem="{Binding SelectedTimeZone}" />
        </StackPanel>
    </Grid>
</Window>

代码:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string _currenttime;
    private TimeZoneInfo _selectedTimeZone;

    public MainWindow()
    {
        InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Background);
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.IsEnabled = true;
        timer.Tick += (s, e) =>
            {
                UpdateTime();
            };
    }

    public List<TimeZoneInfo> TimeZones
    {
        get { return TimeZoneInfo.GetSystemTimeZones().ToList(); }
    }

    public string CurrentTime
    {
        get { return _currenttime; }
        set { _currenttime = value; OnPropertyChanged("CurrentTime"); }
    }

    public TimeZoneInfo SelectedTimeZone
    {
        get { return _selectedTimeZone; }
        set 
        { 
            _selectedTimeZone = value;
            OnPropertyChanged("SelectedTimeZone");
            UpdateTime();
        }
    }

    private void UpdateTime()
    {
        CurrentTime = SelectedTimeZone == null
               ? DateTime.Now.ToLongTimeString()
               : DateTime.UtcNow.AddHours(SelectedTimeZone.BaseUtcOffset.TotalHours).ToLongTimeString();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

时钟:

这篇关于c# wpf 应用程序中的时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆