When I have added a comboBox to the WPF window, how do I add items to the comboBox? Int the XAML code for the design or in NameOfWindow.xaml.cs file?
There are many ways to perform this task. Here is a simple one:
Left Docked StackPanel 2
Bottom Docked StackPanel Left
Next, we have the C# code:
private void myButton_Click(object sender, RoutedEventArgs e)
{
ComboBoxItem cboBoxItem = new ComboBoxItem(); // Create example instance of our desired type.
Type type1 = cboBoxItem.GetType();
object cboBoxItemInstance = Activator.CreateInstance(type1); // Construct an instance of that type.
for (int i = 0; i < 12; i++)
{
string newName = "stringExample" + i.ToString();
// Generate the objects from our list of strings.
ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + newName, newName);
cboBox1.Items.Add(item); // Add each newly constructed item to our NAMED combobox.
}
}
private ComboBoxItem CreateComboBoxItem(ComboBoxItem myCbo, string content, string name)
{
Type type1 = myCbo.GetType();
ComboBoxItem instance = (ComboBoxItem)Activator.CreateInstance(type1);
// Here, we're using reflection to get and set the properties of the type.
PropertyInfo Content = instance.GetType().GetProperty("Content", BindingFlags.Public | BindingFlags.Instance);
PropertyInfo Name = instance.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
this.SetProperty(Content, instance, content);
this.SetProperty(Name, instance, name);
return instance;
//PropertyInfo prop = type.GetProperties(rb1);
}
Note: This is using reflection. If you'd like to learn more about the basics of reflection and why you might want to use it, this is a great introductory article:
If you'd like to learn more about how you might use reflection with WPF specifically, here are some resources:
And if you want to massively speed up the performance of reflection, it's best to use IL to do that, like this:
Fast version of the ActivatorCreateInstance method using IL
Fast Dynamic Property and Field Accessors