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

本文关键字:得到 NullReferenceException 错误 System 抛出 Focus ListboxItem | 更新日期: 2023-09-27 18:02:46

我使用下面的代码,但它抛出一个错误在最后一行

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);
    }
}

错误:未处理异常系统。得到NullReferenceException:
对象引用未设置为对象的实例。
在MyApp.Delogs灵活;> c__DisplayClass3.b__0 ()
在System.Windows.Threading.ExceptionWrapper。InternalRealCall(Delegate callback, Object args, Int32 numArgs)
在MS.Internal.Threading.ExceptionFilterHelper。TryCatchWhen(对象源,委托方法,对象参数,Int32 numArgs,委托catchHandler)

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

尝试检查您是否有SelectedItem,并使用以下

绕过此设置
if (listBoxItem !=null)
          listBoxItem.Focus();