ListboxItem.Focus()抛出System.NullReferenceException错误

时间:2014-05-09 15:14:32

标签: c# focus listboxitem

我正在使用下面的代码,但它在最后一行引发错误

protected override void Append(LoggingEvent loggingEvent)
{
    if (loggingEvent.Level.Name == "INFO")
    {
        FIXOUTUI ui = FIXOUTUI.GetInstance();
        Action action = () =>
        {
            ui.Listbox1.Items.Add(loggingEvent.TimeStamp.ToString("HH:mm:ss") + " " + loggingEvent.RenderedMessage);

            ui.Listbox1.SelectedItem = ui.Listbox1.Items[ui.Listbox1.Items.Count - 1];
            ui.Listbox1.UpdateLayout();

            var listBoxItem = (ListBoxItem)ui.Listbox1
                .ItemContainerGenerator
                .ContainerFromItem(ui.Listbox1.SelectedItem);
            listBoxItem.Focus(); this line throw an error
        };
        ui.Dispatcher.BeginInvoke(action);
    }
}
  

错误:   未处理的异常System.NullReferenceException:
  对象引用未设置为对象的实例   在MyApp.Delogs。<> c__DisplayClass3.b__0()
  在System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,对象args,Int32 numArgs)
  在MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source,Delegate方法,Object args,Int32 numArgs,Delegate catchHandler)

1 个答案:

答案 0 :(得分:0)

尝试检查您是否有SelectedItem并绕过此操作使用以下

if (listBoxItem !=null)
          listBoxItem.Focus();