0

ListBox用 Binding 填充我的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();

两者都不起作用,我不知道为什么?

4

2 回答 2

1

与您使用调度程序添加新项目的方式相同,使用它来更改所选项目:

Dispatcher.BeginInvoke(() => datelistbox.SelectedIndex = 0);
于 2013-08-19T12:32:20.857 回答
1

调度程序调用是异步的,无法保证它们何时运行,因此当您设置选定的索引时,该项目尚不存在。将所有基于 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;
});
于 2013-08-19T16:03:15.563 回答