tags:

views:

20

answers:

2

I have settings dialog with a number of ComboBoxes. More often than not, these ComboBoxes will only have one selectable value. So to make the dialog easier to use I want the ComboBox to autoselect the single value if, and only if, Items.Count == 1 && SelectedItem == null.

I found this but dont want to add additional dependencies if I can avoid it.

I ended up creating a CustomControl based on the ComboBox with a single override:

public class SmartComboBox : ComboBox
{
    public SmartComboBox()
    {
    }

    protected override void OnItemsChanged(
        NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        if (Items.Count == 1 && SelectedItem == null)
        {
            SelectedItem = Items[0];
        }
    }
}
  • Could the same behavior be achieved with triggers/hooks?
  • Is this all I need to do when extending a ComboBox? I mean, will it function like a ComboBox (with the exception of this added behavior) when it comes to styles and such?
+1  A: 

Yes the ComboBox will carry on working perfectly fine, and the other way (personally my prefferend way as i can add mutliple behaviours to a single combobox) is to use Behaviours as suggested in the questions you linked to.

LnDCobra
+1  A: 

Yes, that's it -- it will work identically, otherwise.

I figured this might be the logical endpoint from your previous question about subscribing to the ComboBox events.

Jay
Are you stalking me? ;) But yes, its indeed an alternative approach to the same problem. And I think I'll go with this one.
mizipzor