2013-07-18 18 views
16

Jestem teraz trochę sfrustrowany combobox i mam nadzieję, że ktoś ma odpowiedź na moje pytanie. Problem dotyczy SelectedItem. Kiedy uruchomię swoją aplikację w debugerze, zgłoszę wyjątek odwołania zerowego, jeśli wprowadzę tekst do ComboBox, który pasuje do elementu (tj. .. a, b lub c) w elementach, a następnie usuwam tekst. Jeśli wprowadzę tekst do ComboBox, a to nie pasuje i pozycja (tj .. .. z) w elementach, a następnie usunie tekst, to nie ulega awarii. Takie zachowanie występuje tylko w debugerze. Jeśli uruchomię aplikację na zewnątrz, nie ulegnę awarii. Używam mvvmlight tookit, ale nie sądzę, że ma to coś wspólnego. Moje kodu jest poniżejCombobox SelectedItem DataBinding Wyjątek NullReference

View:

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

modelu:

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

można wyjaśnić nieco więcej, co masz na myśli, gdy mówisz, że wchodzimy i usuwanie elementów? Czy to w interfejsie użytkownika? Lub w kodzie? lub...? – Tim

+1

Po uruchomieniu aplikacji w debugerze właściwość combobox IsEditable = "True". Dlatego mogę dodawać i usuwać tekst z combobox. Przepraszam, będę edytować, aby to wyjaśnić. – poco

+1

Na pierwszy rzut oka twój kod wygląda idealnie i powinien działać za jednym razem. Więc spróbowałem i działało zgodnie z oczekiwaniami. Tak więc podany kod nie stanowi problemu. – Nitesh

Odpowiedz

23

Jest to błąd w .NET Framework 4 (i .NET 4.5, nie w .NET 3.0 i .NET 3.5).

Powoduje to problem z metodą PresentationFramework.dll!MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid(object item).

Patrząc z .NET reflektor, jego kod wygląda następująco:

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

Problem jest następujący wiersz:

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

kod zakłada, że ​​jeśli columnName jest "Item", następnie nieruchomość jest podziałowe i próbuje uzyskać dostęp do pierwszego argumentu za pośrednictwem args[0] i tutaj pojawia się NullReferenceException, ponieważ args jest null, ponieważ właściwość nie jest indeksowana. Po prostu nazywa się "Item".

. Implementatorzy .NET powinni używać PropertyInfo.GetIndexParameters() na info, a jeśli zwrócona tablica nie zawiera elementów zerowych, należy założyć, że właściwość to indeksator. Lub użyj Binding.IndexerName do sprawdzenia (Binding.IndexerName ma wartość "Item[]").

Dlaczego problem powstaje tylko w Visual Studio debugera jest znacznie bardziej subtelny i jest ukryty w następujący sposób: PresentationFramework.dll MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid().

Oto zdemontowany kod:

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

Od item zmienna nie będzie zerowa (to jest rzeczywiście instancją WeakReference która posiada MainViewModel instancji), jedyny warunek, który w przypadku braku metody DetermineWhetherDBNullIsValid(item) nazywa się to, jeśli Wczytano zestaw System.Data.dll, który jest sprawdzany pod numerem AssemblyHelper.IsLoaded(UncommonAssembly.System_Data).

Debuger Visual Studio zawsze ładuje plik System.Data.dll, ponieważ projekt odwołuje się do niego, mimo że go nie używa. Poza debugerem Visual Studio, System.Data.dll ładuje się tylko wtedy, gdy jest używany, co nigdy nie jest, i dlatego aplikacja nie zawiedzie poza Visual Studio.

Masz następujące opcje, aby pozbyć się tego problemu:

  1. Zmiana nazwy własności, który jest związany ComboBox.SelectedItem do jakiejś innej nazwy niż "Item" tak że realizacja buggy .NET nie zakładamy już, że nieruchomość jest podziałowe.
  2. Usuń plik System.Data.dll z referencji projektu, aby nie był ładowany nawet w debugerze Visual Studio.

Uważam, że opcja 2 jest bardziej delikatna, ponieważ może zaistnieć sytuacja, że ​​plik System.Data.dll musi zostać załadowany bezpośrednio przez aplikację lub pośrednio przez inny załadowany zespół.

Więc pójdę z opcją 1.

+2

Potwierdzenie, że obie opcje działają zgodnie z opisem - przetestowane na serwerze VS2012 w sieci docelowej .NET 4.5. Dobra robota @Stipo i dzięki za udostępnienie! Morał tej historii - ** nigdy ** nie nazywa żadnej z właściwości twojego modelu widoku jako "** Przedmiot **" :) – Sevenate

3

jestem w stanie odtworzyć ten po mojej stronie. Dodaj to do kodu combobox:

IsTextSearchEnabled="False" 

Anyways, kto jest zainteresowany w tym problemu, StackTrace dla tego wyjątku jest następujący

PresentationFramework.dll MS.Internal.Data.PropertyPathWorker!. DetermineWhetherDBNullIsValid (pozycja obiektu) + 0xc7 bajty
PresentationFramework.dll! MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid() + 0x64 bajtów
PresentationFramework.dll! MS.Internal.Data.PropertyPathWorker.IsDBNullValidForUpdate.get() + 0x2E bajtów PresentationFramework.dll! MS.Internal.Data.ClrBindingWorker.IsDBNullValidForUpdate.get() + 0xa bajtów PresentationFramework.dll System.Windows.Data.BindingExpression.ConvertProposedValue (wartość obiektu)! + 0x177 bajtów
systemu
PresentationFramework.dll! .Windows.Data.BindingExpressionBase.UpdateValue() + 0x92 bajtów
PresentationFramework.dll! System.Windows.Data.BindingExpression.UpdateOverride() + 0x3d bajty
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.Update() + 0x20 bajtów
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.ProcessDirty() + 0x2f bajtów PresentationFramework.dll! System.Windows.Data.BindingExpress ionBase.Dirty() + 0x40 bajtów
PresentationFramework.dll! System.Windows.Data.BindingExpressionBase.SetValue (System.WindowsDependencyObject d, System.WindowsDependencyProperty dp, wartość obiektu) + 0x24 bajtów
WindowsBase.dll! System.WindowsDependencyObject.SetValueCommon (System.WindowsDependencyProperty dp, wartość obiektu, metryki System.Windows.PropertyMetadata, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType, bool isInternal) + 0x3c4 bajty
WindowsBase.dll! System.WindowsDependencyObject.SetCurrentValueInternal (System.WindowsDependencyProperty dp, wartość obiektu) + 0x35 bajtów
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties() + 0x13f przez tes
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.SelectionChanger.End() + 0x80 bajtów
PresentationFramework.dll! System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem (System.Windows.Controls.ItemsControl.ItemInfo info, bool assumeInItemsCollection) + 0x145 bajtów systemu
PresentationFramework.dll! .Windows.Controls.Primitives.Selector.OnSelectedIndexChanged (System.WindowsDependencyObject d, System.WindowsDependencyChangedEventArgs e) + 0xd9 bajtów
WindowsBase.dll! System.WindowsDependencyObject.OnPropertyChanged (System.WindowsDependencyPropertyChangedEventArgs e) + 0x4d bajtów PresentationFramework.dll! System.Windows.FrameworkElement.OnPropertyChanged (System.WindowsDependencyPropertyChangedEventArgs e) + 0x50 bajtów
WindowsBase.dll! System.Windows .DependencyObject.NotifyPropertyChange (Argumenty System.WindowsDependencyPropertyChangedEventArgs) + 0x3b bajtów
WindowsBase.dll! System.WindowsDependencyObject.UpdateEffectiveValue (System.Windows.EntryIndex entryIndex, System.WindowsDependencyProperty dp, System.Windows.PropertyMetadata metadane, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType) + 0x757 bajtów
WindowsBase.dll! System.Windows.DependencyObject.SetValueCommon (System.Windows.DependencyProperty dp, wartość obiektu, metadane System.Windows.PropertyMetadata, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType, bool isInternal) + 0x2ea bajty
WindowsBa se.dll! System.WindowsDependencyObject.SetCurrentValueInternal (System.WindowsDependencyProperty dp, wartość obiektu) + 0x35 bajtów
PresentationFramework.dll! System.Windows.Controls.ComboBox.TextUpdated (string newText, bool textBoxUpdated) + 0x26e bajtów
System.Windows.Controls.ComboBox.OnEditableTextBoxTextChanged (obiektu nadawcy System.Windows.Controls.TextChangedEventArgs e) + 0x2E bajtów PresentationFramework.dll! System.Windows.Controls.TextChangedEventArgs.InvokeEventHandler (System.Delegate genericHandler PresentationFramework.dll! , object genericTarget) + 0x2c bajtów
PresentationCore.dll! System.Windows.RoutedEventArgs.InvokeHandler (System.Delegate handler, obiekt docelowy) + 0x33 bajtów
PresentationCore.dll! System.W indows.RoutedEventHandlerInfo.InvokeHandler (target obiektu, System.Windows.RoutedEventArgs routedEventArgs) + 0x44 bajtów
System.Windows.EventRoute.InvokeHandlersImpl PresentationCore.dll! (źródło obiektu, System.Windows.RoutedEventArgs args, bool przebił) + 0x1a8 bajtów
PresentationCore.dll! System.Windows.UIElement.RaiseEventImpl (System.WindowsDependencyObject sender, Argumenty System.Windows.RoutedEventArgs) + 0x73 bajtów
PresentationCore.dll! System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs e) + 0x29 bajtów PresentationFramework.dll! System.Windows.Controls.Primitives.TextBoxBase.OnTextChanged (System.Windows.Controls.TextChangedEventArgs e) + 0x5 bajtów
PresentationFramework.dll! System.Windows.Controls. Primitives.TextBoxBase.OnTextContainerChanged (obiekt nadawca, System.Windows.Documents.TextContainerChangedEventArgs e) + 0xe0 bajtów
PresentationFramework.dll! System.Windows.Controls.TextBox.OnTextContainerChanged (obiekt nadawca, System.Windows.Documents.TextContainerChangedEventArgs e) + 0x17d bajtów PresentationFramework.dll! System.Windows.Documents.TextContainer.EndChange (bool skipEvents) + 0xb6 bajtów
PresentationFramework.dll! System.Windows.Documents.TextContainer.System.Windows.Documents.ITextContainer.EndChange (bool skipEvents) + 0xb bajtów PresentationFramework.dll! System.Windows.Documents.TextRangeBase.EndChange (System.Windows.Documents.ITextRange thisRange, bool disableScroll, bool skipEvents) + 0x59 bajtów PresentationFramework.dll! System.Windows.Documents.TextRange.System.Windows.Documents.ITextRange.EndChange (bool disableScroll, skipEvents Bool) + 0x11 bajtów
PresentationFramework.dll! System.Windows.Documents.TextRange.ChangeBlock.System.IDisposable.Dispose() + 0x15 bajtów
PresentationFramework .dll! System.Windows.Documents.TextEditorTyping.OnDelete (obiekt nadawca, argumenty System.Windows.Input.ExecutedRoutedEventArgs) + 0x1a7 bajty
PresentationCore.dll! System.Windows.Input.CommandBinding.OnExecuted (obiekt nadawca, System.Windows .Input.ExecutedRoutedEventArgs e) + 0x65 bajtów PresentationCore.dll! System.Windows.Input.CommandManager.ExecuteCommandBinding (obiektu nadawcy System.Windows.Input.ExecutedRoutedEventArgs e System.Windows.Input.CommandBinding commandBinding) + 0x92 bajtów
PresentationCore.dll! System.Windows.Input.CommandManager.FindCommandBinding (System.Windows.Input.CommandBindingCollection commandBindings, object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) + 0x105 bajtów
PresentationCore.dll! System.Windows.Input.CommandManager.FindCommandBinding (obiekt nadawca, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) + 0x15e bajtów PresentationCore.dll! System.Windows.Input .CommandManager.OnExecuted (obiektu nadawcy System.Windows.Input.ExecutedRoutedEventArgs e) + 0x25 bajtów PresentationCore.dll! System.Windows.UIElement.OnExecutedThunk (obiektu nadawcy System.Windows.Input.ExecutedRoutedEventArgs e) + 0x46 bajtów
PresentationCore.dll! System.Windows.Input.ExecutedRoutedEventArgs.Invok eEventHandler (System.Delegate genericHandler, obiekt docelowy) + 0x3c bajty
PresentationCore.dll! System.Windows.RoutedEventArgs.InvokeHandler (uchwytu System.Delegate, obiekt docelowy) + 0x33 bajtów
PresentationCore.dll! System.Windows.RoutedEventHandlerInfo. InvokeHandler (target obiektu, System.Windows.RoutedEventArgs routedEventArgs) + 0x44 bajtów
System.Windows.EventRoute.InvokeHandlersImpl PresentationCore.dll! (źródło obiektu, System.Windows.RoutedEventArgs args, bool przebił) + 0x1a8 bajtów
PresentationCore.dll ! System.Windows.UIElement.RaiseEventImpl (System.WindowsDependencyObject sender, Argumenty System.Windows.RoutedEventArgs) + 0x73 bajtów
PresentationCore.dll! System.Windows.UIElement.Rais eTrustedEvent (System.Windows.RoutedEventArgs args) + 0x3d bajty
PresentationCore.dll! System.Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs args, bool zaufany) + 0x40 bajtów
PresentationCore.dll! System.Windows.Input .RoutedCommand.ExecuteImpl (parametr obiektu, System.Windows.IInputElement target, bool userInitiated) + 0x105 bajtów
PresentationCore.dll! System.Windows.Input.RoutedCommand.ExecuteCore (parametr obiektu, System.Windows.IInputElement target, bool userInitiated) + 0x59 bajtów PresentationCore.dll! System.Windows.Input.CommandManager.TranslateInput (System.Windows.IInputElement targetElement, System.Windows.Input.InputEventArgs inputEventArgs) + 0x59b bajtów
PresentationCore.dll! System.Windows.UIE lement.OnKeyDownThunk (object sender, System.Windows.Input.KeyEventArgs e) + 0x52 bajtów
PresentationCore.dll! System.Windows.Input.KeyEventArgs.InvokeEventHandler (System.Delegate genericHandler, obiekt genericTarget) + 0x2c bajty
PresentationCore. System.Windows.RoutedEventArgs.InvokeHandler (handler System.Delegate, obiekt docelowy) + 0x33 bajtów
PresentationCore.dll! System.Windows.RoutedEventHandlerInfo.InvokeHandler (target obiektu, System.Windows.RoutedEventArgs routedEventArgs) dll! + 0x44 bajtów
PresentationCore.dll! System.Windows.EventRoute.InvokeHandlersImpl (źródło obiektu, argumenty System.Windows.RoutedEventArgs, bool reRaised) + 0x1a8 bajty
PresentationCore.dll! System.Windows.UIElement.RaiseEventImpl (System.Windows.DependencyObject nadawca, System.Windows.RoutedEventArgs args) + 0x73 bajtów
PresentationCore.dll! System.Windows.UIElement.RaiseTrustedEvent (System.Windows.RoutedEventArgs args) + 0x3d bajty
Systemu PresentationCore.dll! .Windows.UIElement.RaiseEvent (System.Windows.RoutedEventArgs args, bool zaufany) + 0x40 bajtów
PresentationCore.dll! System.Windows.Input.InputManager.ProcessStagingArea() + 0x1f8 bajtów
PresentationCore.dll! System.Windows. Input.InputManager.ProcessInput (wejście System.Windows.Input.InputEventArgs) + 0x45 bajtów PresentationCore.dll! System.Windows.Input.InputProviderSite.ReportInput (System.Windows.Input.InputReport inputReport) + 0x62 bajtów
PresentationCore.dll! System.Windows.Interop.HwndKeyboardInputProvider.ReportInput (System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, Akcje System.Windows.Input.RawKeyboardActions, int scanCode, bool isExtendedKey, bool isSystemKey, int virtualKey) + 0xee bajty PresentationCore.dll! System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction (ref System.Windows.Interop.MSG msg, odniesienie bool) + 0xac bajtów
PresentationCore.dll! System.Windows.Interop. HwndSource.CriticalTranslateAccelerator (ref System.Windows.Interop.MSG MSG System.Windows.Input.ModifierKeys modyfikatory) + 0x94 bajtów
PresentationCore.dll! System.Windows.Interop.HwndSource.OnPreprocessMessage (obiektu param) + 0x12c bajtów
WindowsBase.dll! System.Windows.Thr eading.ExceptionWrapper.InternalRealCall (System.Delegate wywołania zwrotnego, args obiektu, int numArgs) + 0x56 bajtów WindowsBase.dll! MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen (źródło obiektu, metoda System.Delegate, args obiektu, int numArgs, system .Delegate catchHandler) + 0x3a bajtów
WindowsBase.dll! System.Windows.Threading.Dispatcher.LegacyInvokeImpl (System.Windows.Threading.Dispatcher Priorytet priorytetu, timeout System.TimeSpan, metoda System.Delegate, args obiektu, int numArgs) + 0x10e bajty WindowsBase.dll! System.Windows.Threading.Dispatcher.Invoke (Priorytet System.Windows.Threading.DispatcherPriority, Metoda System.Delegate, obiekt arg) + 0x3e bajtów
PresentationCore.dll! System.Windows.Interop.HwndSource. OnPreprocessMessageThunk (ref. System.Windows.Interop.MSG msg, ref bool handled) + 0x93 bajtów
PresentationCore.dll! System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage (ref System.Windows.Interop.MSG msg, ref bool obsługiwane) + 0x33 bajtów
WindowsBase.dll! System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage (ref. System.Windows.Interop.MSG msg) + 0x3c bajtów
WindowsBase.dll! System.Windows.Threading.Dispatcher.PushFrameImpl (System.Windows.Threading.DispatcherFrame frame) + 0x9a bajtów
WindowsBase.dll! System. Windows.Threading.Dispatcher.PushFrame (System.Windows.Threading.DispatcherFrame frame) + 0x49 bajtów
WindowsBase.dll! System.Windows.Threading.Dispatcher.Run() + 0x4b bajtów
Obecny ationFramework.dll! System.Windows.Application.RunDispatcher (ignorowanie obiektu) + 0x17 bajtów
PresentationFramework.dll! System.Windows.Application.RunInternal (okno System.Windows.Window) + 0x6f bajtów PresentationFramework.dll! System.Windows .Application.Run (okno System.Windows.Window) + 0x26 bajtów PresentationFramework.dll! System.Windows.Application.Run() + 0x1b bajtów WpfApplication1.exe! WpfApplication1.App.Main() + 0x59 bajtów C# [ Natywny do zarządzanego przejścia]
[Zarządzane na rodzime przejście]
mscorlib.dll! System.AppDomain.ExecuteAssembly (string assemblyFile, System.Security.Policy.Dowody assemblySecurity, string [] args) + 0x6b bajtów
Microsoft.VisualStudio.HostingProcess.Utilities.dll! Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x27 bajtów
mscorlib.dll! System.Threading.ThreadHelper.ThreadStart_Context (stan obiektu) + 0x6f bajtów
mscorlib.dll! System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback zwrotna, stan obiektu, bool preserveSyncCtx) + 0xa7 bajtów
mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, stan obiektu, bool preserveSyncCtx) + 0x16 bajtów
mscorlib.dll! Sys tem.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback zwrotna, stan obiektu) + 0x41 bajtów
mscorlib.dll! System.Threading.ThreadHelper.ThreadStart() + 0x44 bajtów
[Native do Zarządzane Transition]

+0

Dzięki za poświęcenie czasu, aby na to popatrzeć. Ustawienie tego na False powoduje zatrzymanie awarii, jednak wymaga to również wybrania elementu z ComboBox, aby zaktualizować SelectedItem Binding, zamiast tylko być w stanie go wpisać. Jak jednak powiedziałem, jeśli uruchomisz to bez debuggera, wszystko wydaje się pracować zgodnie z oczekiwaniami. Zjadłem moją głowę na to zachowanie, mając nadzieję, że ktoś może mi powiedzieć, dlaczego. – poco

3

Spróbuj to:

  1. Napisz konwerter

    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. w 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

Dzięki za poświęcenie czasu, aby na to popatrzeć. Rozumiem, że to powstrzyma awarię. Pozostawia to jednak Element w twoim modelu widoku jako nowy Przedmiot. Nie ma powodu, dla którego mogę zobaczyć, że pozycja nie powinna mieć wartości NULL. Jak już wspomniałem powyżej, jeśli uruchomisz to bez debugowania, nie doświadczysz awarii. Interesuje mnie, dlaczego tak się dzieje, a nie sposób obejścia tego problemu. – poco