开发者

Adding Items to a ListBox

I have a WPF main window, which contains a toolbar with buttons and a tabcontrol that is displaying a page with a listbox. The page is hosted on a frame, and the frame is set on the tab I selected.

When I click on a button on my toolbar, a new window pops up with a textbox and a submit button. When I press the submit button, I want to insert the textbox contents into the listbox that's on the main window. However, nothing displays in the listbox. I tried listbox.Items.Add() but it still won't display.

public partial class AddNewCamper : Window
{
    public AddNewCamper()
    {
        InitializeComponent();
    }

    private void btnNewSubmit_Click(object sender, RoutedEventArgs e)
    {
        CampersPage c;

        // Converting string to int b/c thats what camper() takes in.
        int NewAge = Convert.ToInt16(txtNewAge.Text);
        int NewGrade = Convert.ToInt16(txtNewGrade.Text);

        // Create a new person
        Camper person = new Camper(NewAge, NewGrade, txtNewFirstName.Text);
        txtNewFirstName.Text = person.getName();

        // Trying to add the first name of th开发者_运维问答e person to display on the listbox of another window.
        c.testListBox.Items.Add(txtNewFirstName.Text);
    }


You can follow any of the following approaches. But based on your comments I guess solution 3 suits you.

1) Try initializing c first. You can't use an object without allocating memory for it.

2) If you want to use the same object, use the reference of the object created in the MainWindow in the required class. something like this should work:

CampersPage c = [reference to CampersPage object in MainWindow]

then add items to your listbox

3) If you want to use the listbox object, make your CampersPage Class static. Making it static would not require you to initialize your class explicitly.

public static CampersPage {
 // do something here
}

Make sure that you declare your listbox in CampersPage as public.

Then in the class requiring your listbox defined in CampersPage, do the following

CampersPage.testListBox.Items.Add(txtNewFirstName.Text);

4) If the classes are in the same namespace, you can declare listbox as a global public property and access it from rest of the classes in the same namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜