【问题标题】:Can't select item ListBox: InvalidOperationException无法选择项目列表框:InvalidOperationException
【发布时间】:2013-08-20 00:03:15
【问题描述】:

我用绑定到ObservableCollection 填充我的ListBox。这些项目添加到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();

都不行,我不知道为什么?

【问题讨论】:

  • 你是否在工作线程(UI线程除外)中调用PopulateDateListbox
  • PopulateDateListbox 在 page=loaded 事件处理程序中被调用。
  • 发布您收到的错误消息

标签: c# xaml listbox windows-phone


【解决方案1】:

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

Dispatcher.BeginInvoke(() => datelistbox.SelectedIndex = 0);

【讨论】:

  • 哦,我明白了。我通常会因为这样的事情得到 UnauthorizedException!谢谢。
  • @PhilippeMaes 那是因为它不是跨线程访问。由于您使用调度程序将元素添加到列表中,并且由于 PopulateDateListbox 在 UI 线程上执行(您说您是从 page_load 事件处理程序调用它),因此不会添加项目,直到方法已完成执行。因此,您正在尝试选择尚未添加的项目。最好的解决方案是完全删除对调度程序的所有调用。
  • 我明白了。有时很难知道我何时必须使用调度程序。但我还在学习!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2021-04-11
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多