0

I am trying to add a ComboBox in the code to a WPF UserControl. The ComboBox is added as expected and shows the default I set in ComboBox, but when I press it, it does not open up.

This is the code with the Data that is trying to get bound, only part of it:

public class SelectRecentData : INotifyPropertyChanged
{
    public ObservableCollection<ComboBoxItem> projectItems { get; set; }
    private ComboBoxItem _selectedprojectItem;

    public ComboBoxItem SelectedprojectItem
    {
        get
        {
            return _selectedprojectItem;
        }
        set
        {
            this._selectedprojectItem = value;
            this.onPropertyChanged("SelectedprojectItem");
        }
    }
}

This is the code for generating and inserting the ComboBox:

SelectRecentData Data = new SelectRecentData();
ComboBox cbo = new ComboBox();
cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding(){
        bind.Source = Data; //Data is the class mentioned above
        bind.Path = new PropertyPath("projectItems");}
cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding(){
        bind.Source = Data;
        bind.Path = new PropertyPath("SelectedprojectItem");});
cbo.Name = name;
cbo.Margin = new Thickness(0.5,0.5,0.5,0.5);
cbo.Width = 200;
sp.Children.Add(cbo); //sp is the StackPanel

This is the code for test adding items if you press a button on the page:

var defaultvalue = new ComboBoxItem { Content = "Added "+mycounter };
Data.projectItems.Add(defaultvalue);
Data.SelectedprojectItem = defaultvalue;
mycounter++;
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • Dude, what are you trying to do? You are not supposed to be creating / manipulating UI elements in procedural code like that. Post a screenshot of what you need and I can tell you the proper way to do it in WPF. – Federico Berasategui Jun 05 '13 at 21:26
  • I have this working using XAML directly (Binding in XAML and no codebehind for binding and making of ComboBoxes), but I have some pages that sometime will have 8 combo boxes and sometime 15 combo boxes. Today, these are viewed in the page, but empty, since I am not able to dynamically add Combo boxes as needed. – Morten Kiil Finsås Jun 05 '13 at 21:45
  • If you need `N` items of anything, you need to use an `ItemsControl`. WPF's idea of "dynamic" is very different from ancient dinosaur incomplete half-baked UI frameworks such as winforms, that requires a lot of horrible hacks for everything and doesn't support a serious level of data binding. You NEVER create or manipulate UI elements in code in WPF. See [My example](http://stackoverflow.com/a/16116922/643085) of "dynamically" generated ComboBoxes and stuff in WPF (the RIGHT way). – Federico Berasategui Jun 05 '13 at 21:54
  • Thank you HighCore. This seams to be something I can use. I will give it a try tomorrow, and thank you for rapid responce – Morten Kiil Finsås Jun 05 '13 at 22:11

0 Answers0