重置 DataSource 将有效地对 ListBox 进行排序:
listBox1.DataSource = null;
listBox1.DataSource = myBindingList;
listBox1.DisplayMember = "MyField";
但这不是自动的。据我了解,只要通过事件或类似的方式更新 DisplayMember 后面的字段,就应该进行排序......
无论如何,请参阅我的完整测试:
public partial class Form1 : Form
{
public BindingList<ABC> myBindingList = new BindingList<ABC>();
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
myBindingList.Add(new ABC("zzz"));
myBindingList.Add(new ABC("aaa"));
}
private void button2_Click(object sender, EventArgs e) {
myBindingList[0].MyField = "ccc"; // was "zzz"
myBindingList[1].MyField = "ddd"; // was "aaa"
listBox1.DataSource = null;
listBox1.DataSource = myBindingList;
listBox1.DisplayMember = "MyField";
}
private void Form1_Load(object sender, EventArgs e) {
listBox1.DataSource = myBindingList;
listBox1.DisplayMember = "MyField";
}
}
public class ABC {
public string MyField { get; set; }
public ABC(string val) {
MyField = val;
}
}