1

I have two properties I'm setting for two WPF combo boxes: one for Month and one for Day. The MonthIndex property looks like this:

private int monthIndex = DateTime.Today.Month - 1;

public int MonthIndex
{
    get { return monthIndex; }
    set
    {
        if (monthIndex != value)
        {
            monthIndex = value;
            RaisePropertyChanged("MonthIndex");
        }
    }
} 

I need to set the DayIndex property but unlike the Month property, it requires calculation - can't use simple declaration like

private int _dayIndex = DateTime.Today.Day - 1;

Each calendar day can have 0 or more events. e.g., if 6/30 had three events, such events would be stored as 30, 30.1, and 30.2 (in ObservableCollection DaysList and corresponding index for each event).

Below is the XAML, declaration, and method for DayIndex:

View:

<ComboBox Name="cboDay"
          ItemsSource="{Binding DaysList, Mode=OneTime}"
          DisplayMemberPath="fltDay"
          SelectedIndex="{Binding DayIndex, Mode=TwoWay}"
          IsEditable="True" />

ViewModel:

public ObservableCollection<Day> DaysList { get; set; }
private int _dayIndex;

public int DayIndex
{
    get
    {
        // perform some calculation logic;
        return _dayIndex;
    }

    set
    {
        if (_dayIndex != value)
        {
            _dayIndex = value;
            RaisePropertyChanged("DayIndex");
        }
    }
}

How do I handle the declaration for dayIndex so it remains updated as the monthIndex does (so I can use its value with other code)?

Community
  • 1
  • 1
Mark S
  • 103
  • 2
  • 8
  • 1
    Do not perform any calculation in the property getter. Instead calculate the new property value, the set `DayIndex = calculatedValue;`. – Clemens Jul 01 '15 at 16:54
  • Like @Clemens says, I'm sure you don't need to recalculate the value very time. You have to identify the spots where you need to recalculate it (when you load your data; when you change month; and when you create a new event, probably?), and simply call the calculations from there and update the `DayIndex` value accordingly. – almulo Jul 01 '15 at 17:09
  • ItemsSource/SelectedItem binding is a much better (and easier!) pattern than ItemsSource/SelectedIndex. Just keep your references in sync (the instance in SelectedIndex must be in ItemsSource) and you're already done, moving on to the next task. –  Jul 01 '15 at 17:37
  • Clemens - did you mean _dayIndex = calculatedValue; ? – Mark S Jul 02 '15 at 16:41

0 Answers0