I want to build some count down counter. The problem is that my solution display only beginning value 10 and last value 1 after 10 sec. Of course, I've implemented the INotifyPropertyChanged interface. Any suggestions for that solution?
<Button Content="Generuj" Command="{Binding ButtonStart}"></Button>
<TextBox Text="{Binding Counter, Mode=OneWay}"></TextBox>
private void ButtonStartClick(object obj)
{
for (int i = 10; i > 0; i--)
{
System.Threading.Thread.Sleep(1000);
Counter = i;
}
}
With Thread.Sleep you are freezing your GUI. Try using a Timer for your purpose. A timer will run simultaneously to your GUI thread and thus will not freeze it. Also you will need to implement the PropertyChanged Event for your counter Also make sure to set your DataContext
//create a dependency property you can bind to (put into class)
public int Counter
{
get { return (int)this.GetValue(CounterProperty); }
set { this.SetValue(CounterProperty, value); }
}
public static readonly DependencyProperty CounterProperty =
DependencyProperty.Register(nameof(Counter), typeof(int), typeof(MainWindow), new PropertyMetadata(default(int)));
//Create a timer that runs one second and decreases CountDown when elapsed (Put into click event)
Timer t = new Timer();
t.Interval = 1000;
t.Elapsed += CountDown;
t.Start();
//restart countdown when value greater one (put into class)
private void CountDown(object sender, ElapsedEventArgs e)
{
if (counter > 1)
{
(sender as Timer).Start();
}
Counter--;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With