我有几个具有相同项目的组合框。我想将项目放入app.xaml
,以防止代码重复。我可以这样做吗?
<Style x:Key="MyCombo" TargetType="{x:Type ComboBox}">
<Setter Property="Items">
<ComboboxItem Content="item one" />
<ComboboxItem Content="item two" />
</Setter>
</Style>
答案 0 :(得分:3)
您可以创建Style
,将ItemsSource
属性设置为集合:
<Style TargetType="ComboBox" x:Key="MyCombo" xmlns:c="clr-namespace:System.Collections;assembly=mscorlib">
<Setter Property="ItemsSource">
<Setter.Value>
<c:ArrayList>
<ComboBoxItem>item one</ComboBoxItem>
<ComboBoxItem>item two</ComboBoxItem>
</c:ArrayList>
</Setter.Value>
</Setter>
</Style>
您还可以将ComboBox
实例定义为资源:
<ComboBox x:Key="MyCombo" x:Shared="False">
<ComboBoxItem Content="item one" />
<ComboBoxItem Content="item two" />
</ComboBox>
并像这样使用它:
<ContentControl Content="{StaticResource MyCombo}" />
第三个选项是创建一个自定义ComboBox
控件,添加公共ComboBoxItem
:
public class MyCombo : ComboBox
{
public MyCombo()
{
Items.Add(new ComboBoxItem() { Content = "item one" });
Items.Add(new ComboBoxItem() { Content = "item two" });
}
}
并创建一个这样的实例:
<local:MyCombo />