Introduction
A ComboBox is very much helpful when you want to provide the ability to choose one or more items of multiple items in your application to be selected by the user.
This article shows a very simple demo of a ComboBox control.
Step 1
To build a Windows Phone 8.1 application, ensure you have Visual Studio 2013 and the Windows Phone 8.1 SDK installed in your system.
Go to "New Project". Under "Installed" > "Templates" > "Visual C#" > "Store Apps" select "Windows Phone Apps" then select "Blank App (Windows Phone)" and provide it a name as you choose (here I am using "ComboBoxDemoWp8.1").
Step 2
Navigate to the "MainPage.xaml" section of the project and add a "Button" control and a "TextBlock" Control to the Show the Content of item selected from ComboBox.
Finally add a "ComboBox" Control to your project.
- <Grid>
- <Button x:Name="ResultButton" Content="Show Result" FontSize="36" HorizontalAlignment="Left" Height="100"
- Margin="37,478,0,0" VerticalAlignment="Top" Width="326" Click="ResultButton_Click"/>
-
- <TextBlock x:Name="ResultTextBlock" HorizontalAlignment="Left" Height="65" Margin="37,264,0,0" TextWrapping="Wrap"
- Text="" FontSize="36" VerticalAlignment="Top" Width="326"/>
-
- <ComboBox x:Name="ComboBoxMenu" HorizontalAlignment="Left" Height="71"
- Margin="37,70,0,0" VerticalAlignment="Top"
- Width="326">
- <ComboBoxItem Content="First Item" IsSelected="True"/>
- <ComboBoxItem Content="Second Item"/>
- <ComboBoxItem Content="Third Item" />
- <ComboBoxItem Content="Fourth Item"/>
- <ComboBoxItem Content="Fifth Item"/>
- <ComboBoxItem Content="Sixth Item"/>
- </ComboBox>
- </Grid>
Here ComboBoxItem is the children of ComboBox used to add the Items inside the ComboBox. Also the "IsSelected" property can be used in any of the items to which we wanted to be selected initially. By default it's value is "false" for all the ComboBoxItems.
Your MainPage will look like this:
Step 3
Now it's time to add some C# code to the project. Navigate to the "Button" Event Handler in your project and add the following line of code:
- private void ResultButton_Click(object sender, RoutedEventArgs e)
- {
-
-
-
-
-
-
- ResultTextBlock.Text = ((ComboBoxItem)ComboBoxMenu.SelectedItem).Content.ToString();
- }
That's it; just compile and run your project.
Initially when the application launches it may be like this:
Now when you select the ComboBox a flyout window will appear like this:
After selecting any of the items, the content of the item will be reflected in the TextBlock like this:
That's it for the article. If you have any query then feel fee to ask.
In the future articles we will see some of the more cool features and controls of Windows Phone 8.1.