a clock in c# wpf application [closed]

2019-06-11 09:24发布

  • i'm working on c# wpf application and i would like to add a clock to my application:
  • how to make that clock in my application?
  • how to make my application clock not linked to windows clock??
  • how to show clock by different styles in my application?
  • how to make it contains calender, time zone...etc .. and modify these things through my application itself?
  • can i make my time stamp in Database linked to application clock and how to achieve that?

1条回答
狗以群分
2楼-- · 2019-06-11 10:21

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

Here is a small example to get you started

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>

Code:

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

Clock:

enter image description here

查看更多
登录 后发表回答