1

I am currently trying to dynamically add ComboBoxItems to a ComboBox that was also created dynamically. I get an error saying that the ComboBox name does not exist.

Anyone know how I would be able to get around this? Any help is appreciated.

YearGroupRegistersRightSide.Children.Add(new ComboBox { Name = "DynamicCombobox3", SelectedIndex = 0 });

DynamicCombobox3.Children.Add(new ComboBoxItem{Name="Item One", Content="<--- Select --->>"});
2
  • I would argue that in WPF you should do this via databinding (MVVM). The combobox should be instantiated using a template/itemtemplate/contentpresenter and the items should be assigned through a binding as well. If you add more info on what the dynamic combobox is based on one could give a more appropriate answer Commented Mar 25, 2018 at 16:16
  • Take a look at Data Templating Overview. If you're going to dynamically add items to a ComboBox, you should set or bind its ItemsSource property to a collection of item objects (e.g. strings) and use an appropriate DataTemplate (or set DisplayMemberPath) for display. Commented Mar 25, 2018 at 16:16

2 Answers 2

1

Combobox doesn't have a Children property. I suggest you new up your combo first then you can keep a reference to it easily. Like:

ComboBox DynamicCombobox3 = new ComboBox { Name = "DynamicCombobox3", SelectedIndex = 0 };
YearGroupRegistersRightSide.Children.Add(DynamicCombobox3);

DynamicCombobox3.Items.Add(new ComboBoxItem { Name = "Item One" });
Sign up to request clarification or add additional context in comments.

1 Comment

Sure, he should learn mvvm. Maybe use templating to create the combo and probably bind the itemssource to a resource or collection. Or maybe he should be building XAML as xml instead and using xamlreader.parse. Impossible to tell from the code given.
0

I guess the ComboBox is not getting instantiated, try changing the 1st line to the following:

ComboBox DynamicCombobox3 = new ComboBox() { Name = "DynamicCombobox3", SelectedIndex = 0 };

Maybe you are missing the round brackets which call the constructor of ComboBox.

1 Comment

It's of course instantiated, just not assigned to a variable named DynamicCombobox3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.