Search code examples
c#comboboxuwpobservablecollection

c# / UWP Can I bind a combobox to a certain "column " in an observable collection


I want to bind my combobox to a "column" in my observable collection.

            private ObservableCollection<IUList> _ius = new ObservableCollection<IUList>();
                    public ObservableCollection<IUList> IUs
                    {
                        get
                        {
                            return _ius;
                        }
                        set
                        {
                            _ius = value;
                            RaisePropertyChanged("IUs");
                        }
                    }

            public class IUList
                    {

                        public string Identifier { get; set; }


                        public string SourceTrackNumber { get; set; }


                        public string TrackBlockStart { get; set; }


                        public string TrackBlockEnd { get; set; }

                        public IUList(string id, string stn, string tbs, string tbe)
                        {
                            this.Identifier = id;
                            this.SourceTrackNumber = stn;
                            this.TrackBlockStart = tbs;
                            this.TrackBlockEnd = tbe;

                        }

                    }

I want my combobox to be populated with all of the "Identifiers" in my observable collection. I just don't quite know how to accomplish this. Any help is appreciated.

c# / UWP Can I bind a combobox to a certain "column " in an observable collection


Solution

  • Yes, this can be done easily in uwp/wpf using data binding. But you have to read the ItemTemplate code carefully.

    You can write the xaml code like this:

    <ComboBox x:Name="comboBox">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Identifier}"/>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
    

    Then in .cs code

            //Add data
            IUList list1 = new IUList("1", "1", "1", "1");
            IUList list11 = new IUList("11", "1", "1", "1");
            IUList list111 = new IUList("1111", "1", "1", "1");
            IUList list1111 = new IUList("11111", "1", "1", "1");
    
            ObservableCollection<IUList> ius = new ObservableCollection<IUList>();
            ius.Add(list1); ius.Add(list11); ius.Add(list111); ius.Add(list1111);
    
            //Bind source
            comboBox.ItemsSource = ius;
    

    Done! Then you will see

    enter image description here