So, I need a basic wpf application with navigation. For navigation I chose UserControl. There is TextBlock and Button in UserControl, call it for example Home. For Timer I created static class. Here is the following Timer.cs code:
namespace WpfApplication12
{
public static class Timer
{
static DispatcherTimer dt = new DispatcherTimer();
static Stopwatch sw = new Stopwatch();
static string currenttime = string.Empty;
static Timer()
{
dt.Tick += new EventHandler(dt_Tick);
dt.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
public static string Time
{
get
{
return currenttime;
}
}
private static void dt_Tick(object sender, EventArgs e)
{
if (sw.IsRunning)
{
TimeSpan ts = sw.Elapsed;
currenttime = string.Format("{0.00}:{1.00}.{2.00}",
ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
}
}
public static void StartTime()
{
sw.Start();
dt.Start();
}
public static void StopTime()
{
if (sw.IsRunning)
sw.Stop();
}
}
}
So, the problem is when I try to display Timer time on the TextBlock in Home.xaml(UserControl), application stopping and closing every time.
What I have tried:
Here is the Home.xaml(UserControl) code:
<UserControl x:Class="WpfApplication12.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Button Content="Start" Name="btn_Start" Grid.Row="0" Click="btn_Start_Click"/>
<TextBlock Text="" Name="Display" FontSize="36" Grid.Row="1"/>
</Grid>
</UserControl>
Home.xaml.cs:
namespace WpfApplication12
{
public partial class Home : UserControl
{
public Home()
{
InitializeComponent();
}
private void btn_Start_Click(object sender, RoutedEventArgs e)
{
Timer.StartTime();
Display.Text = Timer.Time;
}
}
}
MainWindow.xaml:
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication12"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox>
<local:Home Width="200"/>
</ListBox>
</Grid>
</Window>