In the following article we are going to see the usage of ComboBox control in Windows Phone 8.1. ComboBox represents a combination of non-editable text box and a drop-down list box that allows users to select an item from a list.
Let's start with creating a new project
Open Visual Studio, select "New Project" and choose "Blank App (Windows Phone)" from project type list. Let's name our new project as "ComboBoxControlsApp", you'll see screen similar as shown below.
Hit "OK" button and you'll see screen similar to one shown below, given that you have opened "MainPage.xaml" file on screen.
If you'll notice the default xaml code in "MainPage.xaml" file, you would see an empty Grid control like as follows.
Now we will add a ComboBox, TextBlock and a Button in our application which can either be typed in design editor or can be drag and drop from Toolbox. ComboBox will show the weeks where user can select any week of his choice. TextBlock is there to show the user selection and Button will have an event handler to fetch the selected week and set that value in the TextBlock.
Replace the default Grid with the following xaml code.
In our xaml code ComboBox has PlaceholderText property which is used to set the default value. Every item in the drop-down list is represented by ComboBoxItem which has Content property set with the text to be shown. The TextBlock control will be accessed in the code behind logic to show the currently selected week in the ComboBox control. The Button control will have an event handler to access the selected ComboBox item and set it as a value of TextBlock.
Now our application will look like the following image.
If you closely look at our Button control in the provided xaml code, you might notice that we are missing it's event handler. Let's take your cursor at the Button control and double click over it. Suddenly you will be redirected to the code behind file with an empty event handler like shown below.
In the above code, cmbWeekDays.SelectedValue will be null when we keep default value as the selected one which is defined by following property of ComboBox.
PlaceholderText="Select any week"
If a valid week is selected then condition cmbWeekDays.SelectedValue != null evaluates to true and we are showing its Content in the TextBlock else we are showing the default text "No week selected..." in the TextBlock.
Let's run our application and select Thursday and click on "Show Result" button, we'll see output as shown below.