The <ComboBox /> element represents a ComboBox in XAML. A ComboBox is a collection of ComboBoxItems represented by <CombBoxItem /> element in XAML. This article shows how to create and use a ComboBox control in XAML.
Creating a ComboBox
The following code creates a ComboBox. By default, the ComboBox height and width is full screen.
This is how you set the width and height of the ComboBox control.
<ComboBox Height="25" Width="100" IsSelectionRequired="True">
</ComboBox> |
Adding ComboBox Items
The following code adds items to the the ComboBox.
The output looks like Figure 1. As you can see, you can select any item from the list.
Figure 1. ComboBox with items
Changing ComboBox Item Properties
You can also set ComboBox and its items properties. For example, this code sets the background color of ComboBox to yellow and foreground color to red.
<ComboBox Height="25" Width="100" IsSelectionRequired="True"
HorizontalAlignment="Center" VerticalAlignment="Top"
Background="yellow" Foreground="red">
<ComboBoxItem>C# Corner</ComboBoxItem>
<ComboBoxItem>Longhorn Corner</ComboBoxItem>
<ComboBoxItem>VB.NET Heaven</ComboBoxItem>
</ComboBox>
|
The output looks like Figure 2.
Figure 2. ComboBox with background and foreground color
You can also control the foreground and background of the items seperately. For example, the following code changes the foreground and background of an item to blue and white respectively.
<ComboBoxItem Foreground="blue" Background="White" >C# Corner</ComboBoxItem> |
The output looks like Figure 3.
Figure 3. Setting ComboBox item background and foreground colors
ComboBox with CheckBoxes
Similar to ListBox control, a ComboBox can also have CheckBox items to a ListBox.
<ComboBox Height="25" Width="150" IsSelectionRequired="True"
HorizontalAlignment="Center" VerticalAlignment="Top"
Background="yellow" Foreground="red">
<CheckBox ID="Item1">C# Corner</CheckBox>
<CheckBox ID="Item2">Longhorn Corner</CheckBox>
<CheckBox ID="Item3">VB.NET Heaven</CheckBox>
</ComboBox>
|
The output looks like Figure 4.
Figure 4. ComboBox with check boxes
ListBox with Image CheckBox
The following code adds an image as a ComboBox item.
<ComboBoxItem Foreground="blue" Background="White" >
<Image Source="C:\butterfly.jpg"/></ComboBoxItem>
|
The output looks like Figure 5. Using the same method, you can have a combo box with imaged items
Figure 5. ComboBox with Imaged item
Further Readings
You may also want to read these related articles.
Ask Your Question
Got a programming related question? You may want to post your question here