我使用此article来设置我可以从我的视图模型绑定的SelectionChangedCommand。
以下是我的观点:
<ComboBox Height="20"
SelectedItem="{Binding SelectedName}"
ItemsSource="{Binding NameCollection}"
commandBehaviors:SelectionChangedBehavior.Command="{Binding SelectionChangedCommand}">
在我的视图模型中,SelectionChangedCommand执行方法:
private void SelectionChangedExecuted()
{
// The logic in this method can take up to 30 seconds at times.
}
现在我的问题是,当用户从我的comboBox中选择一个新名称时,最多可能需要30秒,直到他们看到他们的名字被选中。在SelectionChangedExecuted方法完成之前,它将显示旧名称。理想情况下,当他们选择名称时,我希望该名称立即显示,然后他们可以等待30秒。我目前的设置可以实现这一目标吗?
当前行为:
- ComboBox中的当前项目:&#34; Bob&#34;
- 用户选择:&#34;史蒂夫&#34;
- 用户等待30秒,而ComboxBox中的当前项目仍然是&#34; Bob&#34;
-30秒结束,ComboBox中的当前项目:&#34; Steve&#34;
通缉行为:
- ComboBox中的当前项目:&#34; Bob&#34;
-User选择:&#34; Steve&#34;,ComboBox中的当前项目是&#34; Steve&#34;
- 用户等待30秒,而ComboxBox中的当前项目仍然是&#34;史蒂夫&#34;
-30秒结束,ComboBox中的当前项目仍然是:&#34; Steve&#34;
答案 0 :(得分:0)
原因是您在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));
}
}
}