DotNet
DotNet

Reputation: 37

WPF Combobox is not updating when collection changed in Model

WPF Combobox is not updating when collection changed in Model.

I am using ICollectionView for both DataGrid and ComboBox. DataGrid is updating when collection is changed in model, but ComboBox is not updating. Please let me know if there are any alternate ways to do this.

Here is the code

Model-> In Model I have

public ObservableCollection<Product> MyModelProducts

ViewModel-> DataGrid Collection

public ICollectionView MyViewModelProducts
{
  get 
  {   
    return CollectionViewSource.GetDefaultView(MyModel.Instance.MyModelProducts);             
  }
}

ViewModel-ComboBox Collection

public ICollectionView MyViewModelListOfProducts
{
  get 
  {   
    return CollectionViewSource.GetDefaultView(MyModel.Instance.MyModelProducts.Select(p => p.Category).Distinct().ToList<string>());            
  }
}

Code in View-->

<ComboBox ItemsSource="{Binding MyViewModelListOfProducts, Mode=OneWay}" />

Binding MyViewModelProducts to DataGrid

Binding MyViewModelListOfProducts to a ComboBox.

Upvotes: 1

Views: 823

Answers (1)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104721

  1. You have to refer to the selected product in offer to filter
  2. Set IsSynchronizedWithCurrentItem to true in the DataGrid.
  3. Raise a property change of MyViewModelListOfProducts when you want it to update. You subscribe the the MyViewModelProducts.CurrentChanged event and update it from there.
  4. You can have a property DistinctCategories or so in the Product class that does that linq query (and is notified upon change, of course), and then bind the ComboBox to the MyViewModelProducts and point to this property - this I think is the preferred way, unless you think the distinct categories is has really no use in the model layer.

Upvotes: 1

Related Questions