Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update property in UI using MVVM in routine

Tags:

c#

wpf

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;
    }
}
like image 656
Rafal010101 Avatar asked Dec 06 '25 16:12

Rafal010101


1 Answers

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--;
    }
like image 55
Denis Schaf Avatar answered Dec 08 '25 08:12

Denis Schaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!