WPF ComboBox.SelectedValue is null, but .SelectedItem is not; SelectedValuePath selected. What for?

Debugging the weird NullRefException is as follows:

Double-shot to display .SelectedItem

Therefore, when the code refers to .SelectedValue , it crashes.

I can't figure out how .SelectedItem can be set, but .SelectedValue not. The values โ€‹โ€‹displayed in the debugger viewer are correct .SelectedIndex also suitable. ComboBox .ItemsSource set to List<DvcTypes> in code:

 cbAdmDvc.ItemsSource = J790M.DAL.DvcTypes.GetList( ); 

.SelectedValuePath set to XAML:

 <ComboBox Name="cbAdmDvc" DisplayMemberPath="sDvcType" SelectedValuePath="tiDvcType" SelectionChanged="cbAdmDvc_SelectionChanged".. /> 

The drop-down section correctly displays .sDvcType labels later.
A very similar implementation works for a group of other filter combos (7 more).
This happens during the Loaded event for the main window.

+5
source share
1 answer

So far, I cannot explain the observed behavior, but have found a relatively simple workaround:

 private void cbAdmDvc_SelectionChanged( object sender, SelectionChangedEventArgs e ) { if( cbAdmDvc.SelectedIndex < 0 ) return; DvcType tiDvc; /// add this temp variable to capture .SelectedValue if( cbAdmDvc.SelectedValue != null ) tiDvc= (DvcType) cbAdmDvc.SelectedValue; else tiDvc= ((DvcTypes) cbAdmDvc.SelectedItem).tiDvcType; DoSmth( tiDvc ); /// instead of DoSmth( (DvcType)cbAdmDvc.SelectedValue ) } 

Stupid, but it works because .SelectedItem set correctly.
As I said, this is the only ComboBox experiencing such oddities from several ...

EDIT, 2014-Oct-21 :

After making some changes to the application logic, it suddenly turned out that I was considering the same problem with another ComboBox. The potential solution found was combobox-selectedvalue-not-update-from-binding-source , but when I tried to set the initial values โ€‹โ€‹via .SelectedItem instead of .SelectedValue , it turned out even .SelectedValue / worse. So I also tried applying my previous solution, and it worked!

Here is my attempt to explain the observed behavior:
Setting the initial value to the code ( CBox.SelectedValue= smth; ) raises the CBox_SelectionChanged event. For some reason, reading .SelectedValue at this point returns null (as if it is not ready yet), however reading .SelectedItem seems wonderful! Once you exit CBox_SelectionChanged , the event code can correctly read .SelectedValue .

So, if you 1 ) have a _SelectionChanged event _SelectionChanged , 2 ) refer to .SelectedValue inside it and 3 >) set the initial selection via .SelectedValue somewhere else in the code - watch out for null and protect the code! NTN !! :)

+3
source

Source: https://habr.com/ru/post/1202385/


All Articles