如何在不重新插入的情况下刷新ListBox中的项目文本?

问题描述 投票:1回答:4

我有类TestClassToString覆盖(它返回Name字段)。我有TestClass添加到ListBox的实例,在某些时候我需要更改其中一个实例的Name,然后我怎么能刷新它在ListBox的文本?

using System;
using System.Windows.Forms;

namespace TestListBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add(new TestClass("asd"));
            listBox1.Items.Add(new TestClass("dsa"));
            listBox1.Items.Add(new TestClass("wqe"));
            listBox1.Items.Add(new TestClass("ewq"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ((TestClass)listBox1.Items[0]).Name = "123";
            listBox1.Refresh(); // doesn't help
            listBox1.Update(); // same of course
        }
    }

    public class TestClass
    {
        public string Name;

        public TestClass(string name)
        {
            this.Name = name;
        }

        public override string ToString()
        {
            return this.Name;
        }
    }
}
c# .net listbox tostring
4个回答
9
投票

尝试

listBox1.Items[0] = listBox1.Items[0];

2
投票

您的Testclass需要实现INotifyPropertyChanged

public class TestClass : INotifyPropertyChanged
{
    string _name;

    public string Name
    {
        get { return _name;}
        set 
        {
              _name = value;
              _notifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void _notifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
    }

    public TestClass(string name)
    {
        this.Name = name;
    }

    public override string ToString()
    {
        return this.Name;
    }
}

但是,只有在使用不依赖于ToString()但绑定属性Name的列时,这才有效

这可以通过更改代码来完成:

在课堂的某个地方宣布

BindingList<TestClass> _dataSource = new BindingList<TestClass>();

在initializeComponent中写

listBox1.DataSource = _dataSource;

然后在_dataSource而不是Listbox上执行所有操作。


1
投票

你可以使用BindingList:

        items = new BindingList<TestClass>( );
        listBox1.DataSource = items;
        listBox1.DisplayMember = "_Name";

然后刷新列表调用:

        items.ResetBindings( );

编辑:另外不要忘记为Name创建一个get属性

      public string _Name
    {
        get { return Name; }
        set { Name= value; }
    }

0
投票

我遇到了同样的问题,并尝试了各种不同的方法来获取项目的显示文本以实际反映基础项目值。经过所有可用的属性后,我发现这是最简单的。 lbGroupList.DrawMode = DrawMode.OwnerDrawFixed; lbGroupList.DrawMode = DrawMode.Normal; 它触发控件中的相应事件以更新显示的文本。

© www.soinside.com 2019 - 2024. All rights reserved.