A C
A C

Reputation: 139

XAML: Create a resource or template for ComboBoxItems

I have multiple comboboxes with a lot of possible selections. Since it's mostly repeat code, I'm wondering if there is a way I can create a resource or template where I can set the ComboBoxItem once and refer to that key every time I want a Combobox to have the same items.

<ComboBox x:Name="CB1">
    <ComboBoxItem>SomeItem0</ComboBoxItem>
    <ComboBoxItem>SomeItem1</ComboBoxItem>
    <ComboBoxItem>SomeItem2</ComboBoxItem>
    <ComboBoxItem>SomeItem3</ComboBoxItem>
    <ComboBoxItem>SomeItem4</ComboBoxItem>
    <ComboBoxItem>SomeItem5</ComboBoxItem>
    <ComboBoxItem>SomeItem6</ComboBoxItem>
    <ComboBoxItem>SomeItem7</ComboBoxItem>
    <ComboBoxItem>SomeItem8</ComboBoxItem>
    <ComboBoxItem>SomeItem9</ComboBoxItem>
    <ComboBoxItem>SomeItem10</ComboBoxItem>
    <ComboBoxItem>SomeItem11</ComboBoxItem>
    <ComboBoxItem>SomeItem12</ComboBoxItem>
    <ComboBoxItem>SomeItem13</ComboBoxItem>
    <ComboBoxItem>SomeItem14</ComboBoxItem>
    <ComboBoxItem>SomeItem15</ComboBoxItem>
    <ComboBoxItem>SomeItem16</ComboBoxItem>
    <ComboBoxItem>SomeItem17</ComboBoxItem>
    <ComboBoxItem>SomeItem18</ComboBoxItem>
    <ComboBoxItem>SomeItem19</ComboBoxItem>
    <ComboBoxItem>SomeItem20</ComboBoxItem>
<ComboBox>

<ComboBox x:Name="CB2">
    <!--Same Items as above-->
<ComboBox>

<ComboBox  x:Name="CB">
    <!--Same Items as above-->
<ComboBox>

.
.
.

Upvotes: 0

Views: 70

Answers (1)

EMAW2008
EMAW2008

Reputation: 299

you could add an XmlDataProvider in your resource dictionary

    <Window.Resources>
    <XmlDataProvider x:Key="Collection" XPath="/COLLECTION">
    <x:XData>
        <COLLECTION xmlns="">
            <ITEM>Item1</ITEM>
            <ITEM>Item2</ITEM>
            <ITEM>Item3</ITEM>
            <ITEM>Item4</ITEM>
        </COLLECTION>
    </x:XData>
</XmlDataProvider>
</Window.Resources>

then bind to it with the ItemsSource property on the ComboBox

<ComboBox Height="25" Width="100" ItemsSource="{Binding Source={StaticResource Collection},XPath=ITEM}" />

Upvotes: 1

Related Questions