Search code examples
c#wpfxamlcomboboxmvvm-light

Set SelectedItem in a ComboBox


I'm trying to set the SelectedItem in a ComboBox but without any success.

enter image description here

As you can see in the above screenshot it shows the first record from the Product list.

Here is the XAML :

<ComboBox Grid.Column="1"
          Grid.Row="0"
          ItemsSource="{Binding Products}"
          SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
          IsSynchronizedWithCurrentItem="True"
          IsEditable="True"
          DisplayMemberPath="ProductName"
          SelectedValuePath="Id"
          Width="200"
          Height="30"
          VerticalContentAlignment="Center"
          Margin="10 0 0 20" />

The ViewModel :

public Product SelectedProduct
{
    get => _selectedProduct;
    set => Set(ref _selectedProduct, value);
}

And here I set the SelectedProduct :

private void OrderUserControl(Order order)
{
    ShowOrderUserControl = Visibility.Visible;

    Products = _productService.GetProducts();

    if (order == null)
    {
        Order = new Order();

        OrderUserControlTitle = "Nieuwe bestelling toevoegen";
    }
    else
    {
        Order = order;

        SelectedProduct = _productService.GetProductById(Order.ProductId);

        OrderUserControlTitle = "Bestelling aanpassen";
    }
}

Any ideas?


Solution

  • Assuming your Product class have an Id property,

    You can get your SelectedProduct like this using linq instead of using your service again :

    SelectedProduct = Products.Find(p => p.Id == Order.ProductId);
    

    It ensures that your selected product is part of your Products list