tags:

views:

181

answers:

1

I have a combobox which is has itemtemplate applied on it and is bind to a List of entity return using linq. i m using mvvm. It is bind to it successfully but when i set the selected value of it from code at runtime to show the selected value coming from db it doesn't select it. For reference here is my combobox xaml.



SelectedValue="{Binding Path=SelectedManufacturer}"
Grid.Column="3" Grid.Row="2" Margin="20,9.25,68,7.75"
ItemTemplate="{StaticResource ManufacturerDataTemplate}" TabIndex="6"/>

Here is my part from code behind from viewModel.

List currentManufacturers = new List();

tblManufacturer selectedManufacturer = null;

public List CurrentManufacturers { get { return currentManufacturers; } set { currentManufacturers = value; NotifyPropertyChanged("CurrentManufacturers"); } }

    public tblManufacturer SelectedManufacturer
    {
        get
        {
            return selectedManufacturer;
        }
        set
        {
            selectedManufacturer = currentManufacturers.Where(mm => mm.ManufacturerID == Convert.ToInt32(selectedDevice.tblManufacturer.EntityKey.EntityKeyValues[0].Value)).First();
            NotifyPropertyChanged("SelectedManufacturer");
        }
    }
+1  A: 

Here is the sample code snippet:

Xaml for ComboBox:

 <ComboBox ItemsSource="{Binding ManufacturerList}" DisplayMemberPath="Name" SelectedValuePath="ID"
              SelectedItem="{Binding SelectedManufacturer}"/>

ViewModel code :

 public class Manufacturer
{
    public int ID { get; set; }

    public string Name { get; set; }
}





 private List<Manufacturer> _manufactuerlist;
   private Manufacturer _selectedManufacturer;

 private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

#region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    public Manufacturer  SelectedManufacturer
    {
        get
        {
          return _selectedManufacturer;
        }
        set
        {
            _selectedManufacturer = value;
            NotifyPropertyChanged("SelectedManufacturer");
        }
    }

    public List<Manufacturer> ManufacturerList
    {
        get
        {
            return _manufactuerlist;
        }
        set
        {
            _manufactuerlist = value;
            NotifyPropertyChanged("ManufacturerList");
        }
    }

And finally Set the Selected Manufacturer in your view model like this:

SelectedManufacturer = _manufactuerlist.Find(m => m.ID == 2);
rams
I have a DataTemplate which is applied on combobox thus i cannot set displaynamepath property. plz tell some other way to do it.
Syed Mustehsan Ikram
Sorry, above comment written by mistake. Your code helped me to resolve my probelm.
Syed Mustehsan Ikram