C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For event handlers in WPF, please type in the attribute, such as "Loaded" and Visual Studio will create the C# event handler.
Also: We set the SelectionIndex property to 0. This sets the first element in the List in the ComboBox.
Example markup: XAML
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Width="120"
Loaded="ComboBox_Loaded"
SelectionChanged="ComboBox_SelectionChanged"/>
</Grid>
</Window>
Example code: C#
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace WpfApplication9
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
// ... A List.
List<string> data = new List<string>();
data.Add("Book");
data.Add("Computer");
data.Add("Chair");
data.Add("Mug");
// ... Get the ComboBox reference.
var comboBox = sender as ComboBox;
// ... Assign the ItemsSource to the List.
comboBox.ItemsSource = data;
// ... Make the first item selected.
comboBox.SelectedIndex = 0;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ... Get the ComboBox.
var comboBox = sender as ComboBox;
// ... Set SelectedItem as Window Title.
string value = comboBox.SelectedItem as string;
this.Title = "Selected: " + value;
}
}
}
Also: We can read in the items from a text file containing strings, and then use those values (stored in a List or array) as the items.