WPF中是否存在与Form.InvokeRequired等效的内容,例如Dispatcher.InvokeRequired?
答案 0 :(得分:5)
这有点奇怪,因为它没有出现在intellisense中,但你可以使用:
var dispatcher = myDispatcherObject.Dispatcher;
if (dispatcher.CheckAccess()) { /* ... */ }
由于所有UI组件都继承自DispatcherObject
,这应该可以解决您的特定问题,但它并非特定于UI线程 - 它可以用于任何调度程序。
答案 1 :(得分:4)
答案 2 :(得分:3)
想到一个可能的解决方案是:
if ( Dispatcher.Thread.Equals( Thread.CurrentThread ) )
{
Action( );
}
else
{
Dispatcher.Invoke( Action );
}
答案 3 :(得分:0)
如果您正在构建Windows应用商店应用,则上述示例将无效。这是 工作的一个例子。当然需要修改:)
/// <summary>
/// Updates the UI after the albums have been retrieved. This prevents the annoying delay when receiving the albums list.
/// </summary>
/// <param name="albums"></param>
public void UpdateUiAfterAlbumsRetrieved(System.Collections.ObjectModel.ObservableCollection<PhotoAlbum> albums)
{
if (!Dispatcher.HasThreadAccess)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
ddlAlbums.DataContext = albums;
ddlAlbums.IsEnabled = true;
tbxProgress.Text = String.Empty;
ProgressBar.IsIndeterminate = false;
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
});
}
else
{
ddlAlbums.DataContext = albums;
ddlAlbums.IsEnabled = true;
tbxProgress.Text = String.Empty;
ProgressBar.IsIndeterminate = false;
}
}