Eben Vranken
Eben Vranken

Reputation: 13

How to add item to listbox of a different window? WPF

In my MainWindow (see pic) I have a listbox and a button called btnToevoegen, which opens up my second window (see second pic), in that window, a class called oToevoegen gets information for 3 ints.

https://i.sstatic.net/WtSkz.png

https://i.sstatic.net/u1wga.png

Now as you can see, when the user is done putting in the info on the second window, he can press the 'volgende' ('next' in dutch) button. See code

        public void btnVolgende_Click(object sender, RoutedEventArgs e)
        {
            MainWindow wdwMain = new MainWindow();
            Toevoegen oToevoegen = new Toevoegen();

            wdwMain.lstFinanceInfo.Items.Add(oToevoegen);

            wdwMain.lstFinanceInfo.Items.Refresh();

            this.Close();
        }

When that button is pressed, I want the class to be added to the lstBox called, lstFinanceInfo (on my mainWindow), but I can't figure out how. The method I've tried doesn't work.

Upvotes: 0

Views: 929

Answers (2)

Andy
Andy

Reputation: 12276

You have several problems in that code.

When you do

MainWindow wdwMain = new MainWindow();

That creates a new instance of MainWindow. You don't then .Show() this so it's just hanging about in memory. You presumably already have an instance of mainwindow though. Since this is another instance of Mainwindow rather than the one that's visible, you can do whatever you like to it and nothing will visibly change.

It is technically possible to make a control public - BUT - this is bad practice. Don't do that.

Add a public method to MainWindow something like:

    public void AddItem (Toevoegen tv)
    {
        lstFinanceInfo.Items.Add(tv);
    }

Because that's public, you can call it from some other class such as your second window.

All you need to do is get a reference and call that method you added. Application has a mainwindow property which will contain that so grab it out there and cast to Mainwindow:

        MainWindow mw = Application.Current.MainWindow as MainWindow;
        mw.AddItem(oToevoegen);

Upvotes: 1

Mohammed Ibrahim
Mohammed Ibrahim

Reputation: 101

why don't you try wdwMain.lstFinanceInfo.Items.Add(oToevoegen.Text); but first make sure oToevoegen has a Text property (where it has the text you wanna display)

Upvotes: 0

Related Questions