I populate my ListBox with a Binding to an ObservableCollection. The items are added to the ListBox just fine, but when I want to select the first item of the ListBox I get an InvalidOperationException...
Code:
private void PopulateDateListbox()
{
// clear listbox
DateList.Clear();
// get days in month
int days = DateTime.DaysInMonth(currentyear, currentmonth);
// new datetime
DateTime dt = new DateTime(currentyear, currentmonth, currentday);
for (int i = 0; i < (days-currentday+1); i++)
{
// create new dataitem
DateItem di = new DateItem();
di.dayint = dt.AddDays(i).Day.ToString(); // day number
di.day = dt.AddDays(i).DayOfWeek.ToString().Substring(0, 3).ToUpper(); // day string
di.monthint = dt.AddDays(i).Month.ToString(); // month number
di.yearint = dt.AddDays(i).Year.ToString(); // year number
// add dateitem to view
Dispatcher.BeginInvoke(() => DateList.Add(di));
}
// select first item in Listbox
datelistbox.SelectedIndex = 0; // <= InvalidOperationException
}
I also tried:
datelistbox.SelectedItem = datelistbox.Items.First();
Neither works and I don't know why?
PopulateDateListboxin worker thread(other than UI thread)?