简体   繁体   中英

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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM