我遇到了与此几乎相同的问题:
C# 更新绑定到通用列表的组合框 https://stackoverflow.com/questions/433281/c-update-combobox-bound-to-generic-list
但是,我正在尝试更改显示的字符串;不添加、删除或排序。我已经尝试了引用问题中提供的 BindingList 解决方案,但没有帮助。
当我编辑项目时,我可以看到组合框的 DataSource 属性已正确更新,但组合框中显示的内容不是 DataSource 属性中的内容。
我的代码如下所示:
mSearchComboData = new List<SearchData>();
mSearchComboData.Add(new SearchData("", StringTable.PatientID));
mSearchComboData.Add(new SearchData("", StringTable.LastName));
mSearchComboData.Add(new SearchData("", StringTable.LastPhysician));
mSearchComboData.Add(new SearchData("", StringTable.LastExamDate));
mBindingList = new BindingList<SearchData>(mSearchComboData);
SearchComboBox.Items.Clear();
SearchComboBox.DataSource = mBindingList;
SearchComboBox.ValueMember = "Value";
SearchComboBox.DisplayMember = "Display";
...
当我尝试更新内容时,我执行以下操作:
int idx = SearchComboBox.SelectedIndex;
mBindingList[idx].Display = value;
SearchComboBox.Refresh();
EDIT::
RefreshItems 似乎是一个私有方法。我刚刚收到错误消息:
“‘System.Windows.Forms.ListControl.RefreshItems()’由于其保护级别而无法访问”
ResetBindings 没有任何效果。
如果您要更改整个对象,即整个 SearchData 对象,则绑定列表将了解此更改,因此将在内部触发正确的事件,并且组合框将更新。然而,由于您只更新一个属性,因此绑定列表不知道某些内容发生了变化。
您需要做的是让 SearchData 类实现 INotifyPropertyChanged。这是我编写的用于演示的快速示例:
public class Dude : INotifyPropertyChanged
{
private string name;
private int age;
public int Age
{
get { return this.Age; }
set
{
this.age = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
这是一些要测试的代码:
private void button1_Click(object sender, EventArgs e)
{
//Populate the list and binding list with some random data
List<Dude> dudes = new List<Dude>();
dudes.Add(new Dude { Name = "Alex", Age = 27 });
dudes.Add(new Dude { Name = "Mike", Age = 37 });
dudes.Add(new Dude { Name = "Bob", Age = 21 });
dudes.Add(new Dude { Name = "Joe", Age = 22 });
this.bindingList = new BindingList<Dude>(dudes);
this.comboBox1.DataSource = bindingList;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Age";
}
private void button3_Click(object sender, EventArgs e)
{
//change selected index to some random garbage
this.bindingList[this.comboBox1.SelectedIndex].Name = "Whatever";
}
由于我的类现在实现了 INotifyPropertyChanged,因此当某些内容发生更改时,绑定列表会得到“通知”,因此所有这些都将起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)