简体   繁体   中英

Synchronice a DataGrid with a list by a Thread (backgroundWorker). WPF C#

I´m tring to link data from a List to a DataGrid, but when I start the object BackgroundWorker, the main thread has been loaded (with a empty List) before the BackgroundWorker fill the List. How can update or something in order to load the data from the BackgroundWorker?

Constructor of MainWindow, here I declare the BackgroundWorker

```
  public MainWindow()
    {
        InitializeComponent();
        backgroundWorker = new BackgroundWorker();            
    }   

A methot to call the function backgroundWorker_DoWork

```       
  private void referenceBtn_Click(object sender, RoutedEventArgs e)
     {
        backgroundWorker.DoWork += backgroundWorker_DoWork;
        backgroundWorker.RunWorkerAsync();

    }  

If the operation is correct I get a lis of object(ApiProduct) and i save them. I try to link by this method, but it´s static. ```

  public static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (textinPut != null && textinPut.Length >= 3)
        {
            ApiConector apiConector = new ApiConector();
            UpdatedListProducts = apiConector.getProductList(textinPut, 2);
            //dgProducto.ItemsSource = UpdatedListProducts;
        }
    } 

```

 public static List<ApiProduct> UpdatedListProducts
    {
        get { return apiProductsStatic.ToList(); }
        set
        {
            apiProductsStatic = value;
        }
    } 

```

 <Grid HorizontalAlignment="Center" Margin="0,20,0,0"  Width="Auto">
                <DataGrid AutoGenerateColumns="False"  x:Name="dgProducto" CanUserAddRows="False" 
                    ColumnWidth="Auto" IsReadOnly="True" 
                          SelectedCellsChanged="dgProducto_SelectedCellsChanged"
                          EnableColumnVirtualization = "True" EnableRowVirtualization = "True"  
                         ScrollViewer.CanContentScroll ="False" DataGrid.RowHeight ="75" 
                           VerticalAlignment="Top" Width="auto"
                         >
                    <DataGrid.Columns  >
                        <DataGridTemplateColumn Header="IMAGEN">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Image Source="{Binding Image}" Height="40" Width="40" 
                                     VerticalAlignment="Center"/>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn >
                        <DataGridTextColumn Header="NOMBRE" Binding="{Binding NameWhole}" />
                        <DataGridTextColumn Header="REFERENCIA" Binding="{Binding Reference}" />
                        <DataGridTextColumn Header="UBICACION" Binding="{Binding Location}" />
                        <DataGridTextColumn Header="PRECIO" Binding="{Binding Price}" />
                        <DataGridTemplateColumn Header="">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel>
                                        <Button x:Name="imprimirBtn" Content="Imprimir" 
                                        Grid.Column="1" Grid.Row="0" HorizontalAlignment="Left" 
                                        Style="{StaticResource MaterialDesignFlatButton}" 
                                               Click="imprimirBtn_Click"  />
                                    </StackPanel>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>

I don't see any need for static members, every window should have its own Data, and its own event handlers, so you should make them non-static

UpdatedListProducts from name show that the list is regularly in change so is better to make it of type ObservableCollection<ApiProduct> instead of List<ApiProduct> to notify the UI if items add or deleted and reflect that change in UI

here is a good article on how to make UI Responding to changes with an intro to The ObservableCollection and the INotifyPropertyChanged interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM