在 SelectionChangedCommand 的执行完成之前,不会设置组合框选定的项
本文关键字:组合 设置 执行 SelectionChangedCommand | 更新日期: 2023-09-27 18:33:48
我使用本文设置了一个可以从我的视图模型绑定到的 SelectionChangedCommand。
以下是我的观点:
<ComboBox Height="20"
SelectedItem="{Binding SelectedName}"
ItemsSource="{Binding NameCollection}"
commandBehaviors:SelectionChangedBehavior.Command="{Binding SelectionChangedCommand}">
在我的视图中,模型的 SelectionChangedCommand Execute 方法:
private void SelectionChangedExecuted()
{
// The logic in this method can take up to 30 seconds at times.
}
现在我的问题是,当用户从我的 comboBox 中选择新名称时,最多可能需要 30 秒才能看到他们的名字被选中。它将显示旧名称,直到 SelectionChangedExecute 方法完成。理想情况下,当他们选择一个名称时,我希望该名称立即显示,然后他们可以等待 30 秒。我可以使用当前的设置完成此操作吗?
当前行为:
-组合框中的当前项目:"鲍勃">
-用户选择:"史蒂夫">
- 用户等待 30 秒,而 ComboxBox 中的当前项目仍为"Bob">
-30 秒结束,组合框中的当前项目:"史蒂夫">
通缉行为:
-组合框中的当前项目:"鲍勃">
- 用户选择:"史蒂夫",组合框中的当前项目是"史蒂夫">
- 用户等待 30 秒,而 ComboxBox 中的当前项目仍为"史蒂夫">
-30 秒结束,ComboBox 中的当前项目仍然是:"史蒂夫">
原因是
您在 UI 线程上同步执行 SelectionChangedExecuted()
方法。应使用 async
/await
异步执行此操作,以便在后台工作线程上执行代码。
private static async void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Selector selector = (Selector)sender;
if (selector != null)
{
ICommand command = selector.GetValue(CommandProperty) as ICommand;
if (command != null)
{
await Task.Run(() => command.Execute(selector.SelectedItem));
}
}
}