0

I'm setting the values in three combo boxes:Year, Month and Day. The year combo box has data stored in ObservableCollection<Year> YearsList in descending order and can be set with SelectedIndex="0" to always display the current year when the page renders:

View:

<ComboBox Name="cboYear"
          ItemsSource="{Binding YearsList, Mode=OneTime}"
          DisplayMemberPath="year"
          SelectedIndex="0"
          SelectedItem="{Binding SelectedYear, Mode=TwoWay}" />

ViewModel:

public ObservableCollection<Year> YearsList { get; set; }
private Year _selectedYear;

public Year SelectedYear
{
    get
    {            
        return _selectedYear;
    }
    set
    {                
        _selectedYear = value;
        RaisePropertyChanged("SelectedYear");
    }
}

@Will suggests to use a SelectedIndex/SelectedItem approach but doing so with cboYear (i.e., removing SelectedIndex="0") renders a blank default value for the Year combo box. So using this approach, do I need another method as @Clemens and @Almulo suggest to render a default value or can such logic be included in the SelectedYear property?

Community
  • 1
  • 1
Mark S
  • 103
  • 2
  • 8
  • What's this "default value" you speak of? If it's something like "choose a value lol" then you should use a control that has a watermark. If it's one of the members of YearsList (like the current year), simply set SelectedYear to this value (e.g., `Fill(YearsList); SelectedYear = YearsList.First();`) –  Jul 02 '15 at 18:40
  • Year default value = current year, Month default value = current month, etc., yes, the default value is in each list (YearsList, MonthsList, and DaysList)... I'm not understanding your suggestion: `Fill(YearsList); SelectedYear = YearsList.First();` - Is "Fill" a user-defined method that populates a list? And where do I place this statement `SelectedYear = YearsList.First();` in my code? Also not seeing First() method in intellisense. Thanks. – Mark S Jul 02 '15 at 19:40
  • `Fill(something)` is pseudocode for "do whatever the hell it is you do to fill the list". So, after you have values in your YearsList, you take the default value from it and set it as the value of `SelectedYear`. `First()` is an extension method of Linq (more properly known as Linq to Objects), which is found in the `System.Linq` namespace. if you guess what it does, you'll most likely be correct. Get to know and love Linq. –  Jul 05 '15 at 20:30

0 Answers0