MainPage.xaml
<Page
x:Class="UniversalAppTutorials.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UniversalAppTutorials"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel
x:Name="stack_panel1"
Margin="50"
Orientation="Horizontal"
Background="LightPink"
Padding="50"
>
<ComboBox
x:Name="ComboBox1"
SelectionChanged="ComboBox1_SelectionChanged"
Margin="0,175,0,0"
/>
<TextBlock
x:Name="TextBlock1"
Foreground="Crimson"
FontFamily="Calibri"
FontSize="25"
Text="Select a color from ComboBox."
TextWrapping="WrapWholeWords"
Margin="150,175,0,0"
/>
</StackPanel>
</Page>
MainPage.xaml.cs
using Windows.UI.Xaml.Controls;
using Windows.UI;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml;
using Windows.UI.Text;
namespace UniversalAppTutorials
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
// Initialize a new string array
string[] colors = {
"Red",
"Green",
"Blue",
"Yellow",
"Snow",
"Gold",
"Forest Green",
"Medium Sea Green"
};
// Get the ComboBox item collection
ItemCollection ic = ComboBox1.Items;
// Loop through the array elements
for (int index = 0; index < colors.Length; index++) {
// Initialize a new ComboBoxItem instance
ComboBoxItem item = new ComboBoxItem();
// Set item padding
item.Padding = new Thickness(10,5,10,5);
// Set item font size
item.FontSize = 20;
// Set the item content
item.Content = colors[index];
// Set item font
item.FontFamily = new FontFamily("MV Boli");
item.FontWeight = FontWeights.Bold;
item.Foreground = new SolidColorBrush(Colors.Black);
if (index % 2 == 0)
{
// Set rugular item style
item.Background = new SolidColorBrush(Colors.SeaGreen);
}
else {
// Set alternate item style
item.Background = new SolidColorBrush(Colors.MediumSeaGreen);
}
// Add the item to item collection
ic.Add(item);
}
}
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the instance of ComboBox
ComboBox comboBox = sender as ComboBox;
// Get the ComboBox selected item
ComboBoxItem item = (ComboBoxItem)comboBox.SelectedItem;
// Get the ComboBox selected item text
string selectedItemText = item.Content.ToString();
// Finally, display the ComboBox selected item text to text block
TextBlock1.Text = "Selected : " + selectedItemText;
}
}
}