简体   繁体   English

在列表框中仅保留5个项目

[英]keeping only 5 items in a listbox

I want to create a simple listbox, which is binded to a linkedlist. 我想创建一个简单的列表框,该列表框绑定到链表。 The list should only ever hold 5 items at any given time. 该列表在任何给定时间只能容纳5个项目。 When a new item is added, it should check if item count >= 5 and then remove the last item and add the new item to the top. 添加新项目时,应检查是否项目计数>= 5 ,然后删除最后一个项目并将新项目添加到顶部。

To do this, I made this test app: 为此,我制作了这个测试应用程序:

public partial class Form1 : Form
{
    LinkedList<string> list01 = new LinkedList<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        list01.AddFirst("AAA");
        list01.AddFirst("BBB");
        list01.AddFirst("CCC");

        listBox1.DataSource = new BindingSource(list01, "");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (list01.Count >= 5)
            list01.RemoveLast();

        list01.AddFirst(DateTime.Now.ToString());
        listBox1.DataSource = new BindingSource(list01, "");
    }
}

It appears, when ever I add a new item, I have to keep setting the datasource to a new bindingsource for the added item to show on the UI 似乎,每当我添加新项目时,都必须继续将数据源设置为新的绑定源,以使添加的项目显示在UI上

Is there way to initisalise one binding source, and when the items in it changes, auto update the listbox without having to set the datasource every time you add a new item? 有没有办法使一个绑定源流行化,并且当其中的项目更改时,自动更新列表框,而不必每次添加新项目时都设置数据源?

You need a collection which implements collection changed notification. 您需要一个实现集合更改通知的集合。 There are two options you have BindingList<T> and ObservableCollection<T> . BindingList<T>ObservableCollection<T>两个选项。

Pick any one, From your comment it seems you're just looking for AddFirst and RemoveLast . 选择任何一个,从您的评论看来,您只是在寻找AddFirstRemoveLast You can create a extension method yourself which does that. 您可以自己创建一个扩展方法。

public static class BindingListExtension
{
    public static void AddFirst<T>(this BindingList<T> list, T item)
    {
        list.Insert(0, item);
    }

    public static void RemoveLast<T>(this BindingList<T> list)
    {
        list.RemoveAt(list.Count - 1);
    }
}

Based on Sriram Sakthivel's suggestion, I have achieved my requirement like this: 根据Sriram Sakthivel's建议,我达到了这样的要求:

public partial class Form1 : Form
{
    BindingList<string> list01 = new BindingList<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.DataSource = list01;

        list01.Add("AAA");
        list01.Add("BBB");
        list01.Add("CCC");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (list01.Count >= 5)
            list01.RemoveAt(4);

        list01.Insert(0, DateTime.Now.ToString());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM