c#wpf应用程序中的时钟

时间:2013-01-23 00:56:10

标签: c# wpf wpf-controls

  • 我正在使用c#wpf应用程序,我想在我的应用程序中添加一个时钟:
  • 如何在我的应用程序中制作该时钟?
  • 如何让我的应用程序时钟没有链接到Windows时钟??
  • 如何在我的应用程序中以不同的样式显示时钟?
  • 如何让它包含日历,时区等...并通过我的应用程序本身修改这些东西?
  • 我可以在与应用程序时钟链接的数据库中创建时间戳,以及如何实现这一点?

1 个答案:

答案 0 :(得分:4)

制作这样的时钟会非常容易。

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

的Xaml:

<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));
        }
    }
}

时钟:

enter image description here