WPF – Accessing controls in Async

Changing the UI from other threads using Async should be done mostly with $State and DataContext binding as described in the other section

However, there are situations in which you would like to access control, for example, to execute one of its methods

In Async, you can use $SyncHash.Window to access the controls. You need to first use a dispatcher and use Windows method FindName to find your control by providing its name

as in the below example which finds a DataGrid object, adds new items to it, and executes its method to scroll to a certain position:

function Add-Source { Async {

    $SyncHash.Window.Dispatcher.Invoke( { #You need to invoke the dispatcher in order to connect to the controls

    foreach ($item in (1..10000)) {

       $SyncHash.Window.FindName("DataGrid").ItemsSource.Add( #You need to find the control by it's name you assigned

        [PSCustomObject]@{ Action = "test" Result = "test" })


    $DataGrid = $SyncHash.Window.FindName("DataGrid")

    $DataGrid.ScrollintoView($DataGrid.Items[$DataGrid.Items.Count - 1]); }, 'Normal')