2015-05-14 48 views
0

我有多個可選擇的組合框。因爲它主要是重複代碼,所以我想知道是否有一種方法可以創建一個資源或模板,我可以在其中設置ComboBoxItem一次,並且每次我想要一個Combobox都具有相同的項目時引用該鍵。XAML:爲ComboBoxItems創建資源或模板

<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> 

. 
. 
. 
+3

將它們綁定ItemsSource屬性的集合在您的視圖模型(或代碼背後) – Tuco

回答

1

,你可以在你的資源字典添加XmlDataProvider

<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> 

然後綁定到它與組合框

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