.net 从不同线程刷新WPF Gui
我有一个带命令绑定的弹出式Gui.net 从不同线程刷新WPF Gui,.net,wpf,.net,Wpf,我有一个带命令绑定的弹出式Gui <Grid x:Name="popup" Visibility="Hidden" DataContext="{Binding Path=PopupMsg}" > <TextBlock x:Name="tbMessage" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,70,10,0"
<Grid x:Name="popup" Visibility="Hidden" DataContext="{Binding Path=PopupMsg}" >
<TextBlock x:Name="tbMessage" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,70,10,0"
Text="{Binding Path=Message}" FontSize="16"/>
<Button x:Name="btnPopupOk" Grid.Row="1" Grid.Column="2" Content="{Binding Path=OkContent}" Margin="10,40,10,10"
Command="{Binding}" CommandParameter="true" />
</Grid>
</Border>
</Grid>
当我从同一个线程使用它时,它工作正常。当我从Web服务收到一个回调时,它位于另一个线程中,我使用Dispatcher显示消息,我可以在弹出窗口中看到新文本,但绑定不起作用。当我用鼠标单击屏幕时,按钮仍然不可用(CanExecute=false),弹出窗口将更新CanExecute的实际值,按钮将显示为可用
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
popup.Visibility = Visibility.Visible;
popup.Focus();
}));
您需要使用一个调度程序来获取可见性更新,以通过主GUI线程(就像您需要在WinForms中使用Invoke一样) 有关详细信息,请参阅 基本上是这样的
popup.Dispatcher.Invoke(DispatcherPriority.Normal, delegate() { popup.Visibilty = Visibility.Visible; popup.Focus(); });
这是我在更新WPF UI时用于修复任何跨线程调用的代码片段
this.Dispatcher.BeginInvoke(
(Action)delegate()
{
//Update code goes in here
});
希望这有帮助您的问题不在于线程,而在于如何使命令调用
CanExecute
通常只有某些gui事件会导致路由命令更新,而且由于WPF不知道在数据更改时调用CanExecute
,所以它不知道
要手动更新所有路由命令,请调用。如果命令是基于消息的,我会在消息更改时调用它。你的问题是什么?你为什么需要更改按钮的CommandBinding?@dmitri我想他想知道为什么命令只有在点击屏幕后才被更新。这个问题很难分辨,但我认为他已经在做了,基于最后一段代码。
this.Dispatcher.BeginInvoke(
(Action)delegate()
{
//Update code goes in here
});