Let's discuss each.
What a ComboBox Control is -
Combobox is a control that enables a user to select one item or option among multiple ones. Combobox looks like the following in open and closed forms.
Open form,
Use of ComboBox Control
This control has a lot of uses in retail systems and other software where we want to let our end-user select one item from multiple options.
Binding of ComboBox Control
In this control, the data (like you just saw in the above image) is not static in professional development. In real time, case studies are needed to populate a combobox from any data source. This process of loading a control with some dynamic data is called Binding of Control with Data.
Example
Let's make a simple UI first and place a combobox on board. Make a UWP Empty Project in Visual Studio.
Open MainPage.cs form Solution Explorer.
Put this XAML code to make the UI.
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel Orientation="Horizontal" Margin="20">
- <TextBlock>Select Student</TextBlock>
- <ComboBox Name="ComboxBox1" ItemsSource="{x:Bind StuList}" Width="150" Margin="10,0"> </ComboBox>
- </StackPanel>
- </Grid>
Explanation of UI
We have placed two simple controls -
- TextBlock (Contain some text only)
- ComboBox (It has a name and an Itemsource Property)
Itemsource property is placed in an XAML Markup Extension of {x:Bind} that takes a data path. In our case, it is simply the name of object which contains the data to populate.
Code behind of UI
Now, we need to make a simple class of students. Like this.
- public class Students {
- public int ID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public override string ToString() {
- return this.Name;
- }
- }
Add this class to your project.
- Now, open the code behind file of the UI.
- Make a list of students and put all the code in Constructor so that whenever you run the application, the data will be instantiated automatically.
- Make a list of students object in MainPage.xaml.cs Class code behind.
And now, populate the list in constructor.
- public sealed partial class MainPage: Page {
- List < Students > StuList = new List < Students > ();
- public MainPage() {
- this.InitializeComponent();
- StuList.Add(new Students() {
- ID = 1, Name = "Ammar1"
- });
- StuList.Add(new Students() {
- ID = 2, Name = "Ammar2"
- });
- StuList.Add(new Students() {
- ID = 3, Name = "Ammar3"
- });
- StuList.Add(new Students() {
- ID = 4, Name = "Ammar4"
- });
- StuList.Add(new Students() {
- ID = 5, Name = "Ammar5"
- });
- }
Now, run the project. You'll see the bind data.