How to animate the Counter value in UI to increase the value in C# WPF?

2.6k views Asked by At

I want to develop an application in WPF, and same in Windows Phone 8.1. Where I want to increase the value of a variable from 100 to 200, from 200 to 300 and go on. This is a score of the game. Now I want to animate this in the UI. I have written a sample code like this.

<Button Click="Button_Click" >Start</Button>
<TextBlock x:Name="tbvalue" />

So when the button is clicked the value will be from 100 to 200, but this should be displayed in the UI like 101,102,103 ... with incremental value animated in the UI.

I have written the code behind like

private void Button_Click(object sender, RoutedEventArgs e)
{
    while (count < upperLimit)
    {
        count += 1;
        this.Dispatcher.BeginInvoke(new Action<object>(perform), sender);
        System.Threading.Thread.Sleep(100);
    }

    i++;
    upperLimit = i * 100;
}

and in that

private void perform(object obj)
{
    tbvalue.Text = count.ToString();
}  

But using this I am not achieving the counter animation. any ideas or suggestions how to achieve this functionality.

2

There are 2 answers

6
Vishal On

This is what I did and it is working fine.I made a demo wpf application

 public MainWindow()
        {

            InitializeComponent();
            Counter_Timer.Interval = new TimeSpan(0, 0, 1);
            Counter_Timer.Tick += dispatcherTimer_Tick;
            counter.Content = 100;
        }
        private readonly DispatcherTimer Counter_Timer = new DispatcherTimer();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Counter_Timer.Start();
        }

        public void dispatcherTimer_Tick(object sender, object e)
        {
            counter.Content = Convert.ToInt16(counter.Content) + 1;
        if (Convert.ToInt16(counter.Content) >= 200)
        {
            Counter_Timer.Stop();
        }
        }

Xaml File:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button Click="Button_Click" Grid.Row="0" Name="Counter" ></Button>
        <Label Name="counter" Grid.Row="1"></Label>
    </Grid>
0
Muhammad Sulaiman On

ViewModel approach (this will animate text change from 0 to 100 when button clicked)

public MainWindowViewModel()
{
   BtnClicked = new DelegateCommand(() => TextBlockValue += 100);
}

private double value;
public double TextBlockValue
{
    set
    {
        DispatcherTimer counterTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(5),
        };
        counterTimer.Tick += (sender, args) =>
        {
            SetProperty(ref this.value, this.value + 1);
            if (this.value >= value) counterTimer.Stop();
        };
        counterTimer.Start();
    }
    get => value;
}