简体   繁体   中英

Adding items to a listbox on a different class in C# using a second form

I have a form MainWindow which contains a list box to be populated by another form/class Task_details but refuses to add anything on list box in the mainWindow. I tried putting the listbox in the Task_details and it was populated normally. My goal is to use my methods on the text_details class to populate the list box in MainWindow partial class. What else can I do to make this happen?

    public partial class MainWindow : Window {

    private bool isTextChanged = false;
    Task_details details;
    public MainWindow() {
        InitializeComponent();
    }
    private void taskMenuItem_Click(object sender, RoutedEventArgs e) {
        details = new Task_details();
        details.Owner = this;
        details.Show();
    }

On task_details this is my code

  public partial class Task_details : Window {
    MainWindow mW;
    private bool isTextChanged = false;

    public Task_details() {
        mW = new MainWindow();
        InitializeComponent();

    }
    private void addTaskButton_Click(object sender, RoutedEventArgs e) {
        String tName = taskNameTextBox.Text;
        String tDesc = descriptionTextBox.Text;
        Task task = new Task(tName, tDesc);
        mW.taskListBox.Items.Add(task);
    } 

You are creating a new MainWindow in the Task_details constructor instead of passing in the existing one. mW does not refer to the window you think it refers to, but rather to a hidden window you created in the second window itself.

You can fix this easily by doing something like this:

public Task_details(MainWindow mw) {
   this.mW = mW;
   InitializeComponent();
}

And when you create the Task_details window in your MainWindow:

details = new Task_details(this);

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