c# - 动态更改 Winforms ComboBox 中项目的文本

标签 c# .net winforms combobox tostring

我有一个包含自定义类实例的 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/

相关文章:

c# - 随机获取 ExecuteNonQuery 需要打开且可用的连接

c# - Linq 结果到 IEnumerable 无效转换

c# - 如何将 C# 流式传输视频(图像)到 HTML5 客户端?

c# - 删除任务栏的关闭功能

c# - Team Foundation Server 的 "Client"和 "WebApi"库有什么区别?

.net - 使用 Windows 窗体缩放大图片

c# - 如何在asp.net中访问同一类的其他方法中的页面加载方法

.net - 如何编写 .NET 单元测试?

c# - 在C#项目中动态创建文件夹

c# - ToolStripDropDownMenu 在表单最小化和恢复后保持打开状态