简体   繁体   中英

C# WPF click event

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

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);

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM