Alvaro Mendez
Alvaro Mendez

Reputation: 133

Can I add hard-coded ComboBoxItems via a Style?

I have a small app where the same ComboBox appears in multiple places and it always has the same set of items. Instead of doing this every time I use the combo box:

<ComboBox ...>
    <ComboBoxItem Content="1" Tag="1" />
    <ComboBoxItem Content="5" Tag="5" />
    <ComboBoxItem Content="10" Tag="10" />
    <ComboBoxItem Content="50" Tag="50" />
</ComboBox>

I was thinking it'd be better to make the items part of a Style that I could apply to each ComboBox. Does anyone know how to make it work? Thanks!

Upvotes: 2

Views: 2038

Answers (2)

Tim
Tim

Reputation: 15237

As an alternative to what Rachel suggested, if you wanted to keep it all XAML, you could put your items (not ComboBoxItems, but the backing data item) into a Resource and then bind to that resource.

Upvotes: 1

Rachel
Rachel

Reputation: 132558

An alternative method I often use for ComboBoxes with identical item lists is to create a static class with a collection property containing the Items, then bind the ItemsSource to this static property

public static class StaticLists
{
    public static List<int> MyList { get; private set; }

    static Lists()
    {
        MyList = LoadSomeList();
    }
}

and

<ComboBox ItemsSource="{Binding Source={x:Static local:StaticLists.MyList}}"/>

Upvotes: 3

Related Questions