8

I grabbed this code from MSDN. What Im trying to do is similar, but use a list instead of three different strings. so say

List<string> strList = new List<string>();
strList.Add("Created with C#");
strList.Add("Item 2");
strList.Add("Item 3");

  //MSDN CODE BELOW
    cbox = new ComboBox();
        cbox.Background = Brushes.LightBlue;
        cboxitem = new ComboBoxItem();
        cboxitem.Content = "Created with C#";
        cbox.Items.Add(cboxitem);
        cboxitem2 = new ComboBoxItem();
        cboxitem2.Content = "Item 2";
        cbox.Items.Add(cboxitem2);
        cboxitem3 = new ComboBoxItem();
        cboxitem3.Content = "Item 3";
        cbox.Items.Add(cboxitem3);

        cv2.Children.Add(cbox);

Tried to do cbox.Items.Add(strList); Also tried a forloop to loop through each element, but that doesn't work either. Any ideas how I can achieve this?

enter image description here

XAML:

          <Grid x:Name="grid44" DataContext="{StaticResource tBLPERMITSViewSource}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="409">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>
                            <Label Content="SPR PACKET ASSIGMENT" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center" FontWeight="Bold"/>
                            <ComboBox x:Name="sPR_ASSIGNEDComboBox" Grid.Column="1" DisplayMemberPath="SPR_ASSIGNED" HorizontalAlignment="Left" Height="Auto" Text="{Binding SPR_ASSIGNED}" ItemsSource="{Binding Items}" Margin="3,5,-114.35,5" Grid.Row="0" VerticalAlignment="Center" Width="238.35" Background="White" IsReadOnly="True" IsEditable="True" >

                            </ComboBox>
                        </Grid>
Gisiota
  • 343
  • 3
  • 4
  • 12
  • Have you tried setting the .ItemsSource property of the combobox to a list of strings? e.g cbox.ItemsSource = new list{"item1", "item2", "item3"}; – User92 Jul 22 '15 at 11:46
  • I have, it shows up blank. but with the right amount of items in the list though. Not sure whats happening. – Gisiota Jul 22 '15 at 15:25
  • What do you mean by 'it shows up blank'? – User92 Jul 22 '15 at 15:32
  • So if I add say five items to a list, under the combobox ill see five empty slots. Ill add an image so you see what I mean. (in the image: "bro" is brought from the property of the xaml text="{binding field"}". Ill also add the xaml to make things more clear.) the content of combobox is brought from the list, but its not showing the string text. – Gisiota Jul 22 '15 at 15:37
  • Is it a standard WPF combobox, or you have you edited the template for it? – User92 Jul 22 '15 at 15:38
  • You are trying to bind the itemssource of the combobox and programmatically set it at the same time. You've set the displaymemberpath to look for a value on the source, even though you've set the source to a list of strings - the elements in the list dont have 'SPR_ASSIGNED' property to display as a representation in the combo. The question states from code-behind; is this what you want, or do you want to bind to a viewmodel? You could bind to something in the codebehind too by setting the datacontext to itself. – User92 Jul 22 '15 at 15:47
  • hmm, ok tried it on a new combobox and it seemed to work. so something is interfering with it. Thanks for your help. WIsh I could give you the answer. Feel free to write it below and ill check it. Thanks again!.. Just saw your recent comment. Yeah its from a dataset, so I want the initial value to read from the database and then a list of options they can choose from. I think I got it, thanks. – Gisiota Jul 22 '15 at 15:49
  • I've added an answer, i recommend you pick one route or the other, don't try to programmatically set the items, and bind to a source at the same time. I also recommended you take a closer look at the ComboBox class, and look at properties such as ItemsSource, Displaymemberpath, SelectedValue, SelectedValuePath: https://msdn.microsoft.com/en-us/library/system.windows.controls.combobox(v=vs.110).aspx – User92 Jul 22 '15 at 15:58

4 Answers4

9

Set the items programmatically:

Code-behind:

    private void PopulateComboBox()
    {
        cBox.ItemsSource = new List<string> { "Item1", "Item2", "Item3"};
    }

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" />

Bind to a collection of items:

    public class DummyClass
    {
        public int Value { get; set; }
        public string DisplayValue { get; set;}
    }

    public ObservableCollection<DummyClass> DummyClassCollection
    {
        get
        {
            return new ObservableCollection<DummyClass>
            {
                new DummyClass{DisplayValue = "Item1", Value = 1},
                new DummyClass{DisplayValue = "Item2", Value = 2},
                new DummyClass{DisplayValue = "Item3", Value = 3},
                new DummyClass{DisplayValue = "Item4", Value = 4},
            };
        }
    }

XAML:

<ComboBox Width="200" Height="30"  x:Name="cBox" ItemsSource="{Binding DummyClassCollection}" DisplayMemberPath="DisplayValue" />
User92
  • 326
  • 1
  • 6
  • It's worth noting that a list could've been used for the collection since it is returning the same data whenever the get is accessed, but I used an observable collection out of pure habit, which has built in notification of the collection changing, so the combox would be updated were the collection it is bound to change. – User92 Jul 22 '15 at 16:03
3

If you don't want to do this following a binding/mvvm pattern, it is quite simple to just do the following:

foreach (var item in items)
{
    _comboBox.Items.Add(item);
    _comboBox.SelectedValuePath = "ID";
    _comboBox.DisplayMemberPath = "Name";
}

Which can be accessed later like so:

var id = _comboBox.SelectedValue;
Daniel
  • 10,864
  • 22
  • 84
  • 115
0

You can use data binding. Data binding allows you to bind the dynamic data from your list to the combobox and have it generated and filled with the content you are passing through.

Binding WPF Combobox to a Custom List

Community
  • 1
  • 1
CalusV
  • 1
  • 2
0

I solved Add and Remove ComboBox items from code behind simply by synchronization of my dictionary Ienumerable Keys with the ComboBox ItemsSource property, and then making a Refresh() of Items property when adding or removing items:

Dictionary<string,Object> dico=new Dictionary<string,Object>();
dico.Add("obj1",obj1);
dico.Add("obj2",obj2);
dico.Add("obj3",obj3);
...
ComboBox combobox=new ComboBox();
combobox.ItemsSource=dico.Keys;

string key=a_key;
Object obj=an_object;
// add //
if (dico.ContainsKey(key)==false)
{
    dico.Add(key,obj);
    combobox.Items.Refresh();
    combobox.SelectedItem=key;
}
// remove //
if (dico.ContainsKey(key)==true)
{
    dico.Remove(key);
    combobox.Items.Refresh();
}
benjil
  • 1