无法从其他表单添加ListBox项

时间:2016-07-04 07:52:08

标签: c# wpf forms listbox

问题:我有2个表格。一个是ListBox,另一个是Form按钮。我想在第二种形式中触发按钮时添加一个ListBox项。尝试使用以下代码,计算有效,但由于某种原因,它不会将项目添加到ListBox。

使用ListBox的表单:

    public void addList(string sName)
    {
        listBox.Items.Add(sName + " " + Annuitätenrechner.zgErg.ToString("0.00") + "€" + " " + Annuitätenrechner.zmErg.ToString("0.00") + "€");
    }

使用按钮填写表格:

    public void bAdd_Click(object sender, RoutedEventArgs e)
    {
        string sMonate = monate2.Text;
        string sZins = zins2.Text;
        string sName = name2.Text;

        if ((monate2.Text == "" && zins2.Text == "") || (sMonate.Contains('-')) || (sZins.Contains('-')))
        {
            MessageBox.Show("Die eingegebenen Werte müssen größer als 0 sein.");
        }

        else
        {
            Daten data = new Daten();
            data.AnBetrag = int.Parse(betrag2.Text);
            data.AnMonate = int.Parse(monate2.Text);
            data.AnZins = double.Parse(zins2.Text) / 100;

            GlobaleDaten.AlleAnnuitaeten.Add(data);

            Annuitätenrechner annuitätenrechner = new Annuitätenrechner();
            annuitätenrechner.AnRechner(data);

            MainWindow mainwindow = new MainWindow();
            mainwindow.addList(sName);
        }
    }

随时询问您是否需要更多信息。

1 个答案:

答案 0 :(得分:1)

将FormWithListBox的引用发送到FormWithButton,示例:

public class FormWithListBox
{
    private void openFormWithButton()
    {
        var formWithButton = new FormWithButton(this);
        formWithButton.Show();
    }

    public void addList(string sName)
    {
        listBox.Items.Add(...);
    }
}

public class FormWithButton
{
    private readonly FormWithListBox _form;
    public FormWithButton(FormWithListBox form)
    {
        _form = form;
    }

    public void bAdd_Click(object sender, RoutedEventArgs e)
    {
        _form.addList("...BlaBlaBla...");
    }
}