UWP - Perform long view model creation and keep UI responsive

后端 未结 1 515
温柔的废话
温柔的废话 2021-01-24 03:55

I\'ve build this example to show my issue. I need to create a hierarchy to be shown in a treeview, treeview to be bound to the view model. In the good old days of VB6 I would ha

1条回答
  •  没有蜡笔的小新
    2021-01-24 04:35

    The ProgressBar can't response because your loop and the UI are executing on the same thread. While the loop is busy, it blocks the thread and can't update the UI. So you can calls the Task.Run( ) method to create a task and put time-consuming operations inside, then use await to perform asynchronous operations, like below:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        ProgB.Value = 0;
        ProgB.Maximum = ((App)App.Current)._Properties.Count() + 1;
        foreach (PropertyModel aProperty in ((App)App.Current)._Properties)
        {
            await Task.Run(() => _PropVM.Add(new PropertyViewModel(aProperty)));
            ProgB.Value++;
        }
        ProgB.Value = ProgB.Maximum;
    }
    

    0 讨论(0)
提交回复
热议问题