Home > front end >  wpf Update TreeView checkboxes during loop
wpf Update TreeView checkboxes during loop

Time:06-09

I'm starting out in wpf. I have a TreeView in which each item has a checkbox. I'm trying to create an animation in which The checkboxes are checked programmatically inside a loop. After researching the topic for some time, I came up with the following method -

    private void Traverse_Click(object sender, RoutedEventArgs e)
    {
        ItemCollection items = tvMain.Items;
        Task.Factory.StartNew( ()=>
            Dispatcher.Invoke( (Action)(() =>
            {
                foreach (TreeViewItem item in items)
                {
                    UIElement elemnt = getCheckbox();
                    if (elemnt != null)
                    {
                        CheckBox chk = (CheckBox)elemnt;
                        chk.IsChecked = !chk.IsChecked;                           
                        tvMain.Items.Refresh();                           
                        tvMain.UpdateLayout();
                        Thread.Sleep(500);
                    }
                }
            })));

And yet despite all of my attempts the the tree doesn't update inside the loop, only at the end. so the checkboxes are all checked at once. How can I make the tree update inside the loop? Thanks

CodePudding user response:

Replace Thread.Sleep with Task.Delay to "sleep" asynchronously:

private async void Traverse_Click(object sender, RoutedEventArgs e)
{
    ItemCollection items = tvMain.Items;
    foreach (TreeViewItem item in items)
    {
        UIElement elemnt = getCheckbox();
        if (elemnt != null)
        {
            CheckBox chk = (CheckBox)elemnt;
            chk.IsChecked = !chk.IsChecked;
            await Task.Delay(500);
        }
    }
}
  • Related