首页 > 解决方案 > 如何使用按钮单击事件创建对象并将它们添加到列表中?

问题描述

我有一个 UI,它允许用户通过输入名称和属性来创建“鸟”类的自定义对象。我需要一个按钮来将新创建的鸟类添加到“鸟类列表”中。我的代码应该是什么样子?

Bird 类有一个子类“Nest”。鸟可以有多个巢,因此有一个巢列表。

我目前有这个代码,它不起作用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Media.Media3D;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NewBird
{
public partial class MainWindow : Window
 {
        public MainWindow()
 {

    }

    List<Bird> BirdList = new List<Bird>();
    Bird bx = new Bird();
    List<Bird.Nest> NList = new List<Bird.Nest>();

    private void AddNewBird_Click(object sender, RoutedEventArgs e)
    {
        Process tempBird = new Process();     
        string tempName = birdtextbox.Text;
    }


    private void AddNewNest_Click(object sender, RoutedEventArgs e)
    {
        Bird.Nest tempNest = new Bird.Nest();
        NList.Add(tempNest);
    }

    private void Add2List_Click(object sender, RoutedEventArgs e)
    {
        Bird holder = new Bird();
        holder= bx;
        holder.nl = NList;
        BirdList.Add(holder);
        }
    }
}    



public class Bird
    {
        public string BirdName { get; set; }
        public List<Nest> nl { get; set; }
        public Nest nest{ get; set; }
    [Serializable()]
        public class Nest
        {
            public int Number { get; set; }
        }
    }

“Add2List_Click”会覆盖之前的 Bird,而不是向 BirdList 添加新的。

标签: c#wpf

解决方案


这是您当前代码的作用:

private void Add2List_Click(object sender, RoutedEventArgs e)
{
    // Create a new Bird and put it in `holder` variable, so far so good.
    Bird holder = new Bird();

    // Replace the content of `holder` (our new Bird) with an existing Bird!
    // The line `Bird holder = new Bird()` just above became pointless since you never use your new Bird.
    // bx is the Bird that was created earlier in your `MainWindow`.
    holder= bx;
    holder.nl = NList;

    // Now you're adding `holder` to the list, but `holder` is not the new Bird anymore, it's the old one.
    BirdList.Add(holder);
    }
}

您可能想要做的是以下内容:

private void Add2List_Click(object sender, RoutedEventArgs e)
{
    // Create a new Bird and put it in `holder` variable.
    Bird holder = new Bird();

    // Create a new List with two new Nests for our new Bird...
    holder.nl = new List<Bird.Nest> { new Nest(), new Nest() };
    // ...or use the existing list of Nests with this line:
    // holder.nl = NList;

    // Add the new Bird to the list.
    BirdList.Add(holder);
    }
}

推荐阅读