2013-07-18 2 views
16

Ich bin ein bisschen frustriert mit Combobox jetzt und hoffe, jemand hat eine Antwort auf meine Frage. Das Problem liegt bei SelectedItem. Wenn ich meine Anwendung im Debugger starte, wird eine Nullreferenzausnahme ausgelöst, wenn ich Text in die ComboBox eingabe, die mit einem Element (dh .. a, b oder c) in Elementen übereinstimmt, und dann den Text lösche. Wenn ich Text in die ComboBox eintrage und das Item (dh .. z) in Items nicht übereinstimmt und dann den Text lösche, stürzt es nicht ab. Dieses Verhalten tritt nur innerhalb des Debuggers auf. Wenn ich die Anwendung nach draußen laufe, stürze ich nicht ab. Ich benutze das mvvmlight takeit, aber ich denke nicht, dass es etwas damit zu tun hat. Mein Code ist untenCombobox SelectedItem DataBinding NullReference Ausnahme

Ausblick:

<ComboBox IsEditable="True" 
       VerticalAlignment="Top" 
       ItemsSource="{Binding Items}" 
       DisplayMemberPath="Name" 
       SelectedItem="{Binding Item,Mode=TwoWay}"/> 

Modell:

public class Item 
{ 
    public string Name { get; set; } 
    public int Id { get; set; } 
} 

VM:

public MainViewModel() 
    { 
     Items = new List<Item> 
      { 
      new Item {Name="a", Id=0}, 
      new Item {Name="b", Id=1}, 
      new Item {Name="c", Id=2}, 
      }; 
    } 

    /// <summary> 
    /// The <see cref="Items" /> property's name. 
    /// </summary> 
    public const string ItemsPropertyName = "Items"; 

    private List<Item> _items; 

    /// <summary> 
    /// Sets and gets the Items property. 
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary> 
    public List<Item> Items 
    { 
     get 
     { 
      return _items; 
     } 
     set 
     { 
      Set(ItemsPropertyName, ref _items, value); 
     } 
    } 

    /// <summary> 
    /// The <see cref="Item" /> property's name. 
    /// </summary> 
    public const string ItemPropertyName = "Item"; 

    private Item _item; 

    /// <summary> 
    /// Sets and gets the Item property. 
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary> 
    public Item Item 
    { 
     get 
     { 
      return _item; 
     } 
     set 
     { 
      Set(ItemPropertyName, ref _item, value); 
     } 
    } 
+0

können Sie ein wenig mehr erklären, was Sie sich beziehen, wenn Sie sagen, Sie betreten und Gegenstände zu löschen? Ist das in der Benutzeroberfläche? Oder im Code? oder...? – Tim

+1

Wenn ich die Anwendung im Debugger ausführen, ist die Combobox-Eigenschaft IsEditable = "True". Daher kann ich Text aus der Combobox hinzufügen und löschen. Tut mir leid, ich werde bearbeiten, um das klarzustellen. – poco

+1

Auf den ersten Blick sieht Ihr Code perfekt aus und sollte in einem Schuss laufen. Also habe ich es versucht und es hat wie erwartet funktioniert. Der von Ihnen bereitgestellte Code hat also kein Problem. – Nitesh

Antwort

23

Dies ist ein Fehler in .NET Framework 4 ist (und 4.5, .NET nicht in .NET 3.0 und .NET 3.5).

Methode PresentationFramework.dll!MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid(object item) verursacht das Problem.

Sah mit .NET Reflector, sieht seinen Code wie folgt aus:

private bool DetermineWhetherDBNullIsValid(object item) 
{ 
    PropertyInfo info; 
    PropertyDescriptor descriptor; 
    DependencyProperty property; 
    DynamicPropertyAccessor accessor; 
    this.SetPropertyInfo(this._arySVS[this.Length - 1].info, out info, out descriptor, out property, out accessor); 
    string columnName = (descriptor != null) ? descriptor.Name : ((info != null) ? info.Name : null); 
    object arg = ((columnName == "Item") && (info != null)) ? this._arySVS[this.Length - 1].args[0] : null; 
    return SystemDataHelper.DetermineWhetherDBNullIsValid(item, columnName, arg); 
} 

Ausgabe in der folgenden Zeile ist:

object arg = ((columnName == "Item") && (info != null)) ? this._arySVS[this.Length - 1].args[0] : null; 

-Code geht davon aus, dass, wenn columnName"Item" ist, dann Eigenschaft ist Indexer und versucht, auf sein erstes Argument über args[0] zuzugreifen, und hier tritt NullReferenceException auf, weil argsnull ist, da die Eigenschaft kein Indexer ist. Es heißt einfach "Item".

.NET-Implementierer sollten PropertyInfo.GetIndexParameters() auf info verwendet haben, und wenn das zurückgegebene Array keine Nullelemente enthält, stellen Sie sicher, dass die Eigenschaft Indexer ist. Oder verwenden Sie Binding.IndexerName für die Überprüfung (Binding.IndexerName hat den Wert "Item[]").

Warum Problem nur in Visual Studio-Debugger entsteht, ist viel subtiler und es wird in folgenden Methode versteckt: PresentationFramework.dll MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid().Hier

ist eine zerlegte Code:

private void DetermineWhetherDBNullIsValid() 
{ 
    bool flag = false; 
    object item = this.GetItem(this.Length - 1); 
    if ((item != null) && AssemblyHelper.IsLoaded(UncommonAssembly.System_Data)) 
    { 
     flag = this.DetermineWhetherDBNullIsValid(item); 
    } 
    this._isDBNullValidForUpdate = new bool?(flag); 
} 

Da item Variable nicht null sein wird (es ist eigentlich eine Instanz von WeakReference die MainViewModel Instanz enthält), einzige Bedingung für die andernfalls Methode DetermineWhetherDBNullIsValid(item) genannt wird, ist, wenn System.Data.dll Assembly geladen wird, die mit AssemblyHelper.IsLoaded(UncommonAssembly.System_Data) überprüft wird.

Der Visual Studio-Debugger lädt immer System.Data.dll, weil das Projekt es referenziert, obwohl es es nicht verwendet. Außerhalb von Visual Studio-Debugger wird System.Data.dll nur geladen, wenn es verwendet wird, was niemals der Fall ist, weshalb die Anwendung außerhalb von Visual Studio nicht fehlschlägt.

Sie Optionen haben folgende bekommen dieses Problem los:

  1. Eigenschaft benennen, die zu ComboBox.SelectedItem bis zu einem gewissen anderen Namen als "Item" so dass Buggy .NET-Implementierung übernehmen nicht mehr gebunden ist diese Eigenschaft Indexer ist.
  2. Entfernen Sie System.Data.dll aus Projektreferenzen, damit es auch nicht in Visual Studio-Debugger geladen wird.

Ich finde Option 2 zerbrechliche, da Situation entstehen kann, dass System.Data.dll geladen werden muß, entweder direkt durch Ihre Anwendung oder indirekt durch eine andere geladene Baugruppe.

So würde ich mit der Option gehen 1.

+2

Bestätigung, dass beide Optionen wie beschrieben funktionieren - getestet mit VS2012 für .NET 4.5. Gute Arbeit @Stipo und vielen Dank für das Teilen! Die Moral dieser Geschichte - ** Niemals ** nennt eine Eigenschaft Ihres View-Models als "** Item **" :) – Sevenate

3

Ich bin in der Lage, dies zu reproduzieren auf meiner Seite. Fügen Sie diese auf Ihre Combobox Code:

IsTextSearchEnabled="False" 

Anyways, wer sonst noch in diesem Problem interessiert ist, ist die Stacktrace für diese Ausnahme als

PresentationFramework.dll MS.Internal.Data.PropertyPathWorker folgt!. DetermineWhetherDBNullIsValid (Objektposition) + 0xC7 Bytes
PresentationFramework.dll! MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid() + 0x64 Bytes
PresentationFramework.dll! MS.Internal.Data.PropertyPathWorker.IsDBNullValidForUpdate.get() + 0x2e Bytes PresentationFramework.dll! MS.Internal.Data.ClrBindingWorker.IsDBNullValidForUpdate.get() + 0xa Bytes
PresentationFramework.dll! System.Windows.Data.BindingExpression.ConvertProposedValue (Objektwert) + 0x177 Bytes
PresentationFramework.dll!-System .Windows.Data.BindingExpressionBase.UpdateValue() + 0x92 Bytes
PresentationFramework.dll! System.Windows.Data.BindingExpression.UpdateOverride() + 0x3D Bytes
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.Update() + 0x20 bytes
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.ProcessDirty() + 0x2f bytes PresentationFramework.dll! System.Windows.Data.BindingExpress ionBase.Dirty() + 0x40 Bytes
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.SetValue (System.Windows.DependencyObject d, System.Windows.DependencyProperty dp, Objektwert) + 0x24 Bytes
WindowsBase.dll! System.Windows.DependencyObject.SetValueCommon (System.Windows.DependencyProperty dp, Objektwert, System.Windows.PropertyMetadata-Metadaten, bool coerceWithDeferedReference, bool coerceWithCurrentValue, System.Windows.OperationType Operationstyp, bool isInternal) + 0x3c4 bytes
WindowsBase.dll! System.Windows.DependencyObject.SetCurrentValueInternal (System.Windows.DependencyProperty dp, Objektwert) + 0x35 Byte
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties() + 0x13f von tes
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.SelectionChanger.End() + 0x80 Bytes
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem (System.Windows.Controls.ItemsControl.ItemInfo Info, bool assumeInItemsCollection) + 0x145 Bytes
PresentationFramework.dll!-System .Windows.Controls.Primitives.Selector.OnSelectedIndexChanged (System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e) + 0xd9 Bytes
WindowsBase.dll! System.Windows.DependencyObject.OnPropertyChanged (System.Windows.DependencyPropertyChangedEventArgs e) + 0x4d Byte PresentationFramework.dll! System.Windows.FrameworkElement.OnPropertyChanged (System.Windows.DependencyPropertyChangedEventArgs e) + 0x50 Byte
WindowsBase.dll! System.Windows .DependencyObject.NotifyPropertyChange (System.Windows.DependencyPropertyChangedEventArgs args) + 0x3b Bytes
WindowsBase.dll! System.Windows.DependencyObject.UpdateEffectiveValue (System.Windows.EntryIndex ENTRYINDEX, System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata Metadaten, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType Operation) + 0x757 Bytes
WindowsBase.dll! System.Windows.DependencyObject.SetValueCommon (System.Windows.DependencyProperty dp, Objektwert, System.Windows.PropertyMetadata-Metadaten, bool coerceWithDeferedReference, bool coerceWithCurrentValue, System.Windows.OperationType Operationstyp, bool isInternal) + 0x2ea Byte
WindowsBa se.dll! System.Windows.DependencyObject.SetCurrentValueInternal (System.Windows.DependencyProperty dp, Objektwert) + 0x35 Byte
PresentationFramework.dll! System.Windows.Controls.ComboBox.TextUpdated (Zeichenfolge newText, bool textBoxUpdated) + 0x26e Bytes
PresentationFramework.dll! System.Windows.Controls.ComboBox.OnEditableTextBoxTextChanged (object sender, System.Windows.Controls.TextChangedEventArgs e) + 0x2e Bytes PresentationFramework.dll! System.Windows.Controls.TextChangedEventArgs.InvokeEventHandler (System.Delegate genericHandler , object genericTarget) + 0x2c bytes
PresentationCore.dll! System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate-Handler, Objektziel) + 0x33 bytes
PresentationCore.dll! System.W indows.RoutedEventHandlerInfo.InvokeHandler (Zielobjekt, System.Windows.RoutedEventArgs RoutedEventArgs) + 0x44 Bytes
PresentationCore.dll! System.Windows.EventRoute.InvokeHandlersImpl (Objektquelle, System.Windows.RoutedEventArgs args, bool reraised) + 0x1a8 Bytes
PresentationCore.dll! System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject Absender, System.Windows.RoutedEventArgs args) + 0x73 Bytes
PresentationCore.dll! System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs e) + 0x29 bytes PresentationFramework.dll! System.Windows.Controls.Primitives.TextBoxBase.OnTextChanged (System.Windows.Controls.TextChangedEventArgs) e) + 0x5 bytes
PresentationFramework.dll! System.Windows.Controls. Primitives.TextBoxBase.OnTextContainerChanged (object sender, System.Windows.Documents.TextContainerChangedEventArgs e) + 0xe0 Bytes
PresentationFramework.dll! System.Windows.Controls.TextBox.OnTextContainerChanged (object sender, System.Windows.Documents.TextContainerChangedEventArgs e) + 0x17d Bytes PresentationFramework.dll! System.Windows.Documents.TextContainer.EndChange (bool skipEvents) + 0xB6 Bytes
PresentationFramework.dll! System.Windows.Documents.TextContainer.System.Windows.Documents.ITextContainer.EndChange (bool skipEvents) + 0xb bytes PresentationFramework.dll! System.Windows.Documents.TextRangeBase.EndChange (System.Windows.Documents.ITextRange thisRange, bool disableScroll, bool skipEvents) + 0x59 bytes PresentationFramework.dll! System.Windows.Documents.TextRange.System.Windows.Documents.ITextRange.EndChange (bool disableScroll, bool skipEvents) + 0x11 Bytes
PresentationFramework.dll! System.Windows.Documents.TextRange.ChangeBlock.System.IDisposable.Dispose() + 0x15 Bytes
PresentationFramework .dll! System.Windows.Documents.TextEditorTyping.OnDelete (Objektabsender, System.Windows.Input.ExecutedRoutedEventArgs-Argumente) + 0x1a7 Byte
PresentationCore.dll! System.Windows.Input.CommandBinding.OnExecuted (Objektabsender, System.Windows .Input.ExecutedRoutedEventArgs e) + 0x65 Byte PresentationCore.dll! System.Windows.Input.CommandManager.ExecuteCommandBinding (Objektabsender, System.Windows.Input.ExecutedRoutedEventArgs e, System.Windows.Input.CommandBinding commandBinding) + 0x92 Byte
PresentationCore.dll! System.Windows.Input.CommandManager.FindCommandBinding (System.Windows.Input.CommandBindingCollection BefehlBindings, Objektabsender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand Befehl, Bool ausführen) + 0x105 bytes
PresentationCore.dll! System.Windows.Input.CommandManager.FindCommandBinding (Objektabsender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand-Befehl, Bool-Ausführung) + 0x15e bytes PresentationCore.dll! System.Windows.Input .CommandManager.OnExecuted (object sender, System.Windows.Input.ExecutedRoutedEventArgs e) + 0x25 Bytes PresentationCore.dll! System.Windows.UIElement.OnExecutedThunk (object sender, System.Windows.Input.ExecutedRoutedEventArgs e) + 0x46 Bytes
PresentationCore.dll! System.Windows.Input.ExecutedRoutedEventArgs.Invok eEventHandler (System.Delegate genericHandler, Objekt target) + 0x3C
PresentationCore.dll! System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate Handler, Objekt target) Bytes + 0x33 Bytes
PresentationCore.dll! System.Windows.RoutedEventHandlerInfo. InvokeHandler (Zielobjekt, System.Windows.RoutedEventArgs RoutedEventArgs) + 0x44 Bytes
PresentationCore.dll! System.Windows.EventRoute.InvokeHandlersImpl (Objektquelle, System.Windows.RoutedEventArgs args, bool reraiste) + 0x1a8 Bytes
PresentationCore.dll ! System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject-Absender, System.Windows.RoutedEventArgs-Argumente) + 0x73 Byte
PresentationCore.dll! System.Windows.UIElement.Rais eTrustedEvent (System.Windows.RoutedEventArgs args) + 0x3D Bytes
PresentationCore.dll! System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs args, bool trusted) + 0x40 Bytes
PresentationCore.dll! System.Windows.Input .RoutedCommand.ExecuteImpl (Objektparameter, System.Windows.IInputElement-Ziel, bool userInitiated) + 0x105 Byte
PresentationCore.dll! System.Windows.Input.RoutedCommand.ExecuteCore (Objektparameter, System.Windows.IInputElement target, bool userInitiated) + 0x59 Byte PresentationCore.dll! System.Windows.Input.CommandManager.TranslateInput (System.Windows.IInputElement targetElement, System.Windows.Input.InputEventArgs inputEventArgs) + 0x59b bytes
PresentationCore.dll! System.Windows.UIE lement.OnKeyDownThunk (object sender, System.Windows.Input.KeyEventArgs e) + 0x52 Bytes
PresentationCore.dll! System.Windows.Input.KeyEventArgs.InvokeEventHandler (System.Delegate genericHandler, Objekt genericTarget) + 0x2C Bytes
PresentationCore. dll! System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate Handler, Objekt target) + 0x33 Bytes
PresentationCore.dll! System.Windows.RoutedEventHandlerInfo.InvokeHandler (Zielobjekt, System.Windows.RoutedEventArgs RoutedEventArgs) + 0x44 Bytes
PresentationCore.dll! System.Windows.EventRoute.InvokeHandlersImpl (Objektquelle, System.Windows.RoutedEventArgs-Argumente, bool reRaised) + 0x1a8 Byte
PresentationCore.dll! System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject Absender, System.Windows.RoutedEventArgs args) + 0x73 Bytes
PresentationCore.dll! System.Windows.UIElement.RaiseTrustedEvent (System.Windows.RoutedEventArgs args) + 0x3D Bytes
PresentationCore.dll!-System .Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs args, vertrauenswürdiger Bool) + 0x40 Bytes
PresentationCore.dll! System.Windows.Input.InputManager.ProcessStagingArea() + 0x1f8 Bytes
PresentationCore.dll! System.Windows. Input.InputManager.ProcessInput (System.Windows.Input.InputEventArgs-Eingabe) + 0x45 Byte PresentationCore.dll! System.Windows.Input.InputProviderSite.ReportInput (System.Windows.Input.InputReport eingabebericht) + 0x62 bytes
PresentationCore.dll! System.Windows.Interop.HwndKeyboardInputProvider.ReportInput (System.IntPtr hwnd, System.Windows.Input.InputMode Modus, int Zeitstempel, System.Windows.Input.RawKeyboardActions Aktionen, int scanCode, bool isExtendedKey, bool isSystemKey, int virtualKey) + 0xee Bytes PresentationCore.dll! System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction (Referenz System.Windows.Interop.MSG msg, ref bool behandelt) + 0xac bytes
PresentationCore.dll! System.Windows.Interop. HwndSource.CriticalTranslateAccelerator (ref System.Windows.Interop.MSG msg, System.Windows.Input.ModifierKeys Modifikatoren) + 0x94 Bytes
PresentationCore.dll! System.Windows.Interop.HwndSource.OnPreprocessMessage (Objekt param) + 0x12C Bytes
WindowsBase.dll! System.Windows.Thr eading.ExceptionWrapper.InternalRealCall (System.Delegate-Rückruf, Objektargumente, int numArgs) + 0x56 Byte WindowsBase.dll! MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen (Objektquelle, System.Delegate-Methode, Objektargumente, int numArgs, System .Delegate catchHandler) + 0x3a Byte
WindowsBase.dll! System.Windows.Threading.Dispatcher.LegacyInvokeImpl (System.Windows.Threading.DispatcherPriority-Priorität, Timeout System.TimeSpan, System.Delegate-Methode, Objektargumente, int numArgs) + 0x10e Bytes WindowsBase.dll! System.Windows.Threading.Dispatcher.Invoke (System.Windows.Threading.DispatcherPriority-Priorität, System.Delegate-Methode, Objekt arg) + 0x3e Bytes
PresentationCore.dll! System.Windows.Interop.HwndSource. OnPreprocessMessageThunk (ref System.Windows.Interop.MSG msg, ref bool behandelt) + 0x93 bytes
PresentationCore.dll! System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage (ref System.Windows.Interop.MSG msg, ref bool behandelt) + 0x33 Bytes
WindowsBase.dll! System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage (ref System.Windows.Interop.MSG msg) + 0x3C Bytes
WindowsBase.dll! System.Windows.Threading.Dispatcher.PushFrameImpl (System.Windows.Threading.DispatcherFrame Rahmen) + 0x9A
WindowsBase.dll! System-Bytes. Windows.Threading.Dispatcher.PushFrame (System.Windows.Threading.DispatcherFrame-Rahmen) + 0x49 bytes
WindowsBase.dll! System.Windows.Threading.Dispatcher.Run() + 0x4b Byte
Present actionFramework.dll! System.Windows.Application.RunDispatcher (Objekt ignorieren) + 0x17 bytes
PresentationFramework.dll! System.Windows.Application.RunInternal (System.Windows.Window-Fenster) + 0x6f bytes PresentationFramework.dll! System.Windows .Application.Run (System.Windows.Window-Fenster) + 0x26 bytes PresentationFramework.dll! System.Windows.Application.Run() + 0x1b bytes WpfApplication1.exe! WpfApplication1.App.Main() + 0x59 bytes C# [ Native to Managed Transition]
[Auf nativen Übergang verwaltet]
mscorlib.dll! System.AppDomain.ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string [] args) + 0x6B Bytes
Microsoft.VisualStudio.HostingProcess.Utilities.dll! Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x27 Bytes
mscorlib.dll! System.Threading.ThreadHelper.ThreadStart_Context (Objektzustand) + 0x6F Bytes
mscorlib.dll! System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext ExecutionContext, System.Threading.ContextCallback Rückruf, Objektzustand, bool preserveSyncCtx) + 0xA7 Bytes
mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback-Callback, Objektstatus, Bool preserveSyncCtx) + 0x16 Byte mscorlib.dll! Sys tem.Threading.ExecutionContext.Run (System.Threading.ExecutionContext ExecutionContext, System.Threading.ContextCallback Rückruf, Objektzustand) + 0x41 Bytes
mscorlib.dll! System.Threading.ThreadHelper.ThreadStart() + 0x44 Bytes
[Nativ zu Managed Transition]

+0

Danke, dass Sie sich die Zeit genommen haben, sich das anzusehen. Wenn Sie dies auf False setzen, wird der Absturz gestoppt. Dazu müssen Sie jedoch ein Element aus der ComboBox auswählen, um die SelectedItem-Bindung zu aktualisieren, anstatt sie einfach eingeben zu müssen. Wie gesagt, wenn Sie dies ohne den Debugger ausführen, scheint alles arbeiten bei erwartet. Ich habe mir bei diesem Verhalten den Kopf zerbrochen und gehofft, dass mir jemand den Grund dafür nennen kann. – poco

3

Try This:

  1. schreiben einen Konverter

    public class NullToItemConverter : IValueConverter 
    { 
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
         return value; 
        } 
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
         if (value == null) 
          return new Item(); 
         else 
          return value; 
        } 
    } 
    
  2. in XAML

    <Window.Resources> 
        <local:NullToItemConverter x:Key="nullToItemConverter"/> 
    </Window.Resources 
    

    ...

    <ComboBox IsEditable="True" 
         VerticalAlignment="Top" 
         ItemsSource="{Binding Items}" 
         DisplayMemberPath="Name" 
         SelectedItem="{Binding Item, Mode=TwoWay , Converter={StaticResource nullToItemConverter}}"/> 
    
+0

Danke, dass Sie sich die Zeit genommen haben, sich das anzuschauen. Ich verstehe, dass dies den Absturz stoppen wird. Dies lässt jedoch Item in Ihrem Viewmodel als neues Item übrig. Es gibt keinen Grund, dass ich sehen kann, dass Item nicht auf null gesetzt werden kann. Wie ich oben sagte, wenn Sie dies ohne Debuggen ausführen, werden Sie den Absturz nicht erleben. Ich bin daran interessiert, warum das passiert, nicht wirklich die Problemumgehung. – poco