Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Gui refresh from different Thread

Tags:

.net

wpf

I have a popup Gui with command binding,

 <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> 

in the C# file i bind the command:

   CommandBinding okCommandBinding = new CommandBinding(OkCommand);
   okCommandBinding.Executed += popupButtons_Executed;
    okCommandBinding.CanExecute += okCommandBinding_CanExecute;
    CommandBindings.Add(okCommandBinding);
    btnPopupOk.Command = OkCommand;

Its working fine when I use it from the same Thread, when I get a callback from Web Service which is in a different thread I use Dispatcher to show a message, i can see the new text in the popup but the binding isn't working the button remaining unavailable (CanExecute = false), When I click on the screen with the mouse, the popup update the real value of CanExecute and the button is appear available.

System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
                popup.Visibility = Visibility.Visible;
                popup.Focus();

            }));  
like image 600
YairT Avatar asked Dec 07 '22 06:12

YairT


1 Answers

this is the code snippet I use to fix any cross thread calls when updating a WPF UI.

 this.Dispatcher.BeginInvoke(
            (Action)delegate()
        {
            //Update code goes in here
        });

Hope this helps

like image 100
Alastair Pitts Avatar answered Dec 11 '22 08:12

Alastair Pitts