动态更改项目的文本中的WinForms组合框组合、项目、动态、文本中

2023-09-04 01:11:13 作者:你在触不到的界限

我有一个WinForms 组合框包含自定义类的实例。当项目被首次添加到组合框的项目集合时,的ToString 方法是在每个人的电话。

I have a Winforms ComboBox that contains instances of a custom class. When the items are first added to the Items collection of the ComboBox, the ToString method is call on each of them.

然而,当用户更改应用程序在运行的语言,的ToString 方法变化的结果。

However when the user changes the language the application is running in, the result of the ToString method changes.

因此​​,我怎么能获得组合框来呼吁所有项目的的ToString 方法再次无需拆卸所有从组合框项目,并把它们添加回来?

Therefore how can I get the ComboBox to call the ToString method on all items again without having to remove all items from the ComboBox and adding them back in?

推荐答案

感谢svick,RefreshItems()的工作,但因为它是受保护的(所以只能由子类的称呼)我不得不这样做。

Thanks svick, RefreshItems() work, however as it is protected (so can only be called by a subclass) I had to do

public class RefreshingComboBox : ComboBox
{
    public new void RefreshItem(int index)
    {
        base.RefreshItem(index);
    }

    public new void RefreshItems()
    {
        base.RefreshItems();
    }
}

我刚才已经给了ToolStripComboBox做同样的,但它是一个有点困难,因为你不能继承的Combro框包含,我做了

I have just had to do the same for a ToolStripComboBox, however it was a bit harder as you can not subclass the Combro box it contains, I did

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);
        }
    }
}

我不得不做同样的行程,停止不必要的事件,对于正常CombroBox,通过重写OnSelectedValueChanged,OnSelectedItemChanged和OnSelectedIndexChanged,为code是一样的,因为我还没有把它列入这里ToolStripComboBox。

I had to do the same trip to stop unwanted events for the normal CombroBox, by overriding OnSelectedValueChanged, OnSelectedItemChanged and OnSelectedIndexChanged, as the code is the same as for the ToolStripComboBox I have not included it here.