Dynamically changing the text of items in a Winforms ComboBox

后端 未结 4 1944
野趣味
野趣味 2020-12-18 08:08

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

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 08:13

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

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

    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.

提交回复
热议问题