views:

368

answers:

3

I've got two combo's 'Make' and 'Model', they've got their SelectedValue properties bound to an Vehicle object with a ModelID and a MakeID.

Heres Model ...

<ComboBox DisplayMemberPath="Description" ItemsSource="{Binding Path=ModelSpecs}" SelectedValue="{Binding Path=Vehicle.ModelID}" SelectedValuePath="ID" />

A user can search for Vehicles in a seperate control and this swaps out the underlying Vehicle object. Everything works fine if your switching between vehicles of the same Make, however if the Make changes I go away to the database and reload the ModelSpec collection. The combo dosnt display the Model Description because the binding needs to be refreshed.

My current work-around is to add this at the end of the method thats reloading the Models - it works fine, but is not a particularly elegent solution.

        var modelID = ViewModel.Vehicle.ModelID;
        ViewModel.Vehicle.ModelID = string.Empty;
        ViewModel.Vehicle.ModelID = modelID;

Basically I'm just triggering the INotifyPropertyChanged ...

    private string _modelID;
    public string ModelID
    {
        get { return _modelID; }
        set 
        {
            if (_modelID == value) return;
            _modelID = value;
            OnPropertyChanged("ModelID");
        }
    }

I can think of a couple of similar inelegant solutions - but there must be a better way?! Any help appreciated!

A: 

Well, this is probably just another "inelegant" solution, but one more correct way would be to get the BindingExpression from the combo-box and call BindingExpression.UpdateSource.

Charlie
His code and his tags suggest he's using Model-View-ViewModel, which would make this a no-no.
Anderson Imes
+1  A: 

Just make ModelSpec collection observable (i.e. implement INotifyCollectionChanged yourself, or use ObservableCollection class for it).

Pavel Minaev
A: 

Thanks for you assistance, in the end this did the trick and I prefer it to my first workaround.

It seems fine to me, but I guess others may gasp in horror? Please feel free to comment if so!

ModelSpecs is on my ManageVehicleViewModel so it dosnt seem that out of place to have the extra PropertyChanged call.

    private IEnumerable<ModelSpec> _modelSpecs;
    public IEnumerable<ModelSpec> ModelSpecs
    {
        get
        {
            return _modelSpecs;
        }
        set
        {
            if (_modelSpecs == value) return;
            _modelSpecs = value;
            OnPropertyChanged("ModelSpecs");
            OnPropertyChanged("Vehicle");
        }
    }
Andy Clarke