0

I wonder why click event does not show me the hp value of every loop. Its only shows me hp at the start and 0 at the end

private void button_Click(object sender, RoutedEventArgs e)
    {
        while (player.Hp > 0)
        {
            int vypocet = player.Damage(player2);
            player.Hp = vypocet;
            label.Content = vypocet;
        }
    }

This should be everything you need to know So as i said its only show me start hp and hp after whole fight and i dont know why its not show me other numbers if i am using while loop

2 Answers 2

2

The reason is that the event handler runs on the UI thread. This means, the changed value can be reflected in the user interface only after the whole loop ends.

If you wanted to show the progress, you would have to run the computation on another thread and use the Dispatcher to notify the UI thread about the changes.

An alternative is to yield the UI thread regularly to give the UI a chance to update. This is however not very clean.

await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
Sign up to request clarification or add additional context in comments.

Comments

1

Because UI controls will be updated after button_Click method exits.

Try change method to asynchronous and use Task.Delay which will "release" UI thread for updating controls

private async void button_Click(object sender, RoutedEventArgs e)
{
    while (player.Hp > 0)
    {
        int vypocet = player.Damage(player2);
        player.Hp = vypocet;
        label.Content = vypocet;
        await Task.Delay(100);
    }
}

1 Comment

Wow thats really awesome. Thanks for it ! very useful for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.