我使用绑定到ListBox
填充ObservableCollection
。这些项目已添加到ListBox
中,但是当我想要选择ListBox
的第一项时,我会得到InvalidOperationException
...
代码:
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
}
我也尝试过:
datelistbox.SelectedItem = datelistbox.Items.First();
既不起作用,也不知道为什么?
答案 0 :(得分:1)
与使用调度程序添加新项目的方式相同,使用它来更改所选项目:
Dispatcher.BeginInvoke(() => datelistbox.SelectedIndex = 0);
答案 1 :(得分:1)
Dispatcher调用是异步的,无法保证它们何时运行,因此当您设置所选索引时,该项目尚不存在。将所有基于UI的工作整合到一个调用中 -
List<DateItem> items = new List<DateItem>();
for (int i = 0; i < (days-currentday+1); i++)
// Create your items and add them to the list
Dispatcher.BeginInvoke(() =>
{
DateList.ItemsSource = items;
DateList.SelectedIndex = 0;
});