Search code examples
c#wpfcomboboxdefaultdefault-value

Display default value into ComboBox without set NAME (WPF)


I have ComboBox:

<ComboBox ItemsSource="{Binding Path=MonthDaysList}" IsSynchronizedWithCurrentItem="True"/>

Here is method to generate MonthDaysList data:

public ObservableCollection<string> MonthDaysList { get; internal set; }
public void GetMonths() {
   MonthDaysList = new ObservableCollection<string>();
   foreach (var item in MyConceptItems) {
            MonthDaysList.Add(item.DateColumn);
   }}

ObservableCollection & Binding are working fine, but it's not displayed default/first item into ComobBox:

enter image description here

It's possible to resolve it without set up Name of ComboBox?


Solution

  • Define a string source property in the view model and bind the SelectedItem property of the ComboBox to this one:

    <ComboBox ItemsSource="{Binding Path=MonthDaysList}" SelectedItem="{Binding SelectedMonthDay}"/>
    

    Make sure that you implement the INotifyPropertyChanged interface if you intend to set the source property dynamically:

    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<string> _monthDaysList;
        public ObservableCollection<string> MonthDaysList
        {
            get { return _monthDaysList; }
            internal set { _monthDaysList = value; OnPropertyChanged(); }
        }
    
    
        private string _selectedMonthDay;
        public string SelectedMonthDay
        {
            get { return _selectedMonthDay; }
            internal set { _selectedMonthDay = value; OnPropertyChanged(); }
        }
    
        public void GetMonths()
        {
            MonthDaysList = new ObservableCollection<string>();
            if (MyConceptItems != null && MyConceptItems.Any())
            {
                foreach (var item in MyConceptItems)
                {
                    MonthDaysList.Add(item.DateColumn);
                }
                SelectedMonthDay = MonthDaysList[0];
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }