我有一个包含自定义类实例的 Winforms ComboBox
。当项目首次添加到 ComboBox
的 Items 集合时,将对每个项目调用 ToString
方法。
但是,当用户更改应用程序运行的语言时,ToString
方法的结果也会发生变化。
因此,我怎样才能让 ComboBox
再次对所有项目调用 ToString
方法,而不必从 ComboBox
中删除所有项目,并且把它们加回去?
最佳答案
谢谢 svick,RefreshItems() 可以工作,但是因为它是 protected (所以只能由子类调用)我不得不这样做
public class RefreshingComboBox : ComboBox
{
public new void RefreshItem(int index)
{
base.RefreshItem(index);
}
public new void RefreshItems()
{
base.RefreshItems();
}
}
我不得不为 ToolStripComboBox 做同样的事情,但是它有点难,因为你不能子类化它包含的 Combro 框,我做到了
public class RefreshingToolStripComboBox : ToolStripComboBox
{
// We do not want "fake" selectedIndex change events etc, subclass that overide the OnIndexChanged etc
// will have to check InOnCultureChanged them selfs
private bool inRefresh = false;
public bool InRefresh { get { return inRefresh; } }
public void Refresh()
{
try
{
inRefresh = true;
// This is harder then it shold be, as I can't get to the Refesh method that
// is on the embebed combro box.
//
// I am trying to get ToString recalled on all the items
int selectedIndex = SelectedIndex;
object[] items = new object[Items.Count];
Items.CopyTo(items, 0);
Items.Clear();
Items.AddRange(items);
SelectedIndex = selectedIndex;
}
finally
{
inRefresh = false;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (!inRefresh)
{
base.OnSelectedIndexChanged(e);
}
}
}
我必须通过覆盖 OnSelectedValueChanged、OnSelectedItemChanged 和 OnSelectedIndexChanged 来做同样的事情来阻止普通 CombroBox 不需要的事件,因为代码与 ToolStripComboBox 的代码相同,我没有在此处包含它。
关于c# - 动态更改 Winforms ComboBox 中项目的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064109/