Displaying Clock according to the time zone selected in WPF application

Posted: April 30, 2013 by Sagar Wasule in Asp.Net, Programming Concepts, WPF

Hi evereyone I’m back with a new post, here I had a requirement for displaying digital clock on my WPF application so have done some development with that respect.

The code for the same is written below:

Xaml :

<Grid DataContext="{Binding ElementName=UI}">
        <StackPanel>
            <TextBlock Text="{Binding CurrentTime}" />
            <ComboBox ItemsSource="{Binding TimeZones}" 
                         SelectedItem="{Binding SelectedTimeZone}" />
        </StackPanel>
    </Grid>

on Xaml.cs


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 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 in WPF

Clock in WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s