Don't use local variable for the timer, timer will be disposed after TimerMetod ends, timer must be a class member.
Use DispatcherTimer. For WPF this is better option than System.Threading.Timer
Threading.Timer calls delegate on non-UI thread unlike DispatcherTimer. This could be issue when you code interacts with UI.
public partial class MainWindow : Window
{
private readonly DispatcherTimer _dispatcherTimer;
private int _count;
public MainWindow()
{
_dispatcherTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_dispatcherTimer.Tick += OnTimer;
InitializeComponent();
}
private void OnTimer(object source, EventArgs e)
{
_count++;
text.Text = "Count:" + _count;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_dispatcherTimer.Start();
}
}
XAML Code
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Start Timer" Click="Button_Click"></Button>
<TextBlock Grid.Row="1" x:Name="text"></TextBlock>
</Grid>