Search code examples
c#wpfdatagrid

WPF Grid not showing content


I'm using a Window with a Grid which loads Objects from a MongoDB. These Object contains Lists. Now I want to Load a List from one of these Objects. This is the Source from the Window:

    public void btn_load_Click(object sender, RoutedEventArgs e)
    {
        MainWindow M = new MainWindow();
       
        ArtikelLaden();
        M.RefreshGrid();

        Close();
        
    }        
    public void ArtikelLaden()
    {

        MainWindow M = new MainWindow();
        rowindexArtikel = dg_Artikel.SelectedIndex;
        Artikel B = new Artikel();
        B = artikelList[rowindexArtikel];
        M.loadArtikel(B);
    }

The List should get loaded in the MainWindow:

public void loadArtikel(Artikel B)
    {
        dg_test.ItemsSource = null;
        dg_test.ItemsSource = B.kaufList;
        dg_test.Items.Refresh();
        MessageBox.Show(dg_test.HasItems.ToString());
        MessageBox.Show(dg_test.Items.Count.ToString());

        dg_Teile.ItemsSource = null;
        dg_Teile.ItemsSource =B.teilList;
        dg_Teile.Items.Refresh();

        //dg_Teile.Items.Refresh();
        //dg_BauGrp.ItemsSource = B.bauList ;
    }
    public void RefreshGrid()
    {
        //dg_Kaufteile.UpdateLayout();
        //dg_Kaufteile.Items.Refresh();
        //dg_Teile.UpdateLayout();
        MessageBox.Show(dg_Kaufteile.HasItems.ToString());
        MessageBox.Show(dg_Kaufteile.Items.Count.ToString());
    }

When you see some curious things in the source is just because I've tested now thousands of possibilities. But the Grids in the MainWindow always simply stays empty.

The first MsgBox says that the grid has Content. Later in second MsgBox in the Refresh Method it says its empty?!

When I load the Lists in the first Window it works. The Grids have AutoColumn enabled.


Solution

  • You are creating a new instance of MainWindow but you probably want to access the already existing one that you see on the screen. Try this:

    public void btn_load_Click(object sender, RoutedEventArgs e)
    {
        MainWindow M = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    
        ArtikelLaden(M);
        M.RefreshGrid();
    
        Close();
    }
    
    public void ArtikelLaden(MainWindow M)
    {
        rowindexArtikel = dg_Artikel.SelectedIndex;
        Artikel B = new Artikel();
        B = artikelList[rowindexArtikel];
        M.loadArtikel(B);
    }