Search code examples
c#wpfcombobox

WPF C# Combobox blank SelectedItem SelectedValue


I am working with a combo box in WPF/C# and I am having and issue that is a little confusing for me. On the combobox , I have the SelectedValue that is passing the value (TaxID) to the object on the VM, also, I have the SelectedItem that is passing the selected object from the combobox to a property on the VM. When I open a record from a Data Grid for editing, the SelectedItem is causing the combobox to be blank, it is not loading the value stored in the db. Upon removing the SelectedItem property the combobox loads properly on open for editing. I need to pass the selected object from the combobox to a property on the VM, any help is much appreciated!

    <ComboBox x:Name="cboPractice" 
    ItemsSource="{Binding Path=PracticesList}"
    DisplayMemberPath="TaxName"
    SelectedValuePath="TaxID"
    SelectedValue="{Binding Path=SiteVisitScheduleCurrent.TaxID, 
                                 UpdateSourceTrigger=PropertyChanged}"
    SelectedItem="{Binding Path=SelectedPractice, UpdateSourceTrigger=PropertyChanged}"
    >
   <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
             <i:InvokeCommandAction Command="{Binding Path=PracticeSelectionChangedCommand}"
                                    CommandParameter="{Binding ElementName=cboPractice, 
                                                      Path=SelectedItem.TaxID}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

Solution

  • The SelectedValue/SelectedValuePath and SelectedItem properties are not meant to be used both at the same time.

    SelectedValue and SelectedValuePath would be used when you are binding to a collection of objects but you want to return a specific property of the objects you are binding to instead the entire object.

    I would suggest removing the SelectedValue and SelectedValuePath Bindings and simply rely on the SelectedItem Binding. You won't need the InteractionTrigger for the SelectionChanged event.

    <ComboBox ItemsSource="{Binding Path=PracticesList}"
              DisplayMemberPath="TaxName"
              SelectedItem="{Binding Path=SelectedPractice}" />
    

    Your VM would have something like this:

    private Practice _mySelectedPractice;
    
    public Practice SelectedPractice
    {
        get => _selectedPractice;
        set => _selectedPractice = value;
    }
    

    When the ComboBox selection has changed your SelectedItem will be updated in your VM's SelectedPractice property.

    In your VM's SelectedPractice setter, you can chose to do whatever else you need to when the selection has changed.

    Here is another article that explains SelectedItem vs. SelectedValue and SelectedValuePath: Difference between SelectedItem, SelectedValue and SelectedValuePath