2014-05-09 5 views
0

J'utilise le code ci-dessous, mais il est une erreur lancer la dernière ligneListboxItem.Focus() renvoie une erreur System.NullReferenceException

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

ERROR: Unhandled Exception System.NullReferenceException:
Object reference not set to an instance of an object.
at MyApp.Delogs.<>c__DisplayClass3.b__0()
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

Répondre

0

essayer de vérifier si vous avez un SelectedItem et de contourner cela, utilisez les suivant

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