Sanjeev S
Sanjeev S

Reputation: 624

How to set the value If the combobox does not change the value in WPF MVVM pattern

In my WPF application I have a combo box. It binds data by MVVM design pattern. It works fine.

enter image description here

In the XAML

 <ComboBox x:Name="comboBox1" ItemsSource="{Binding ValetType}" DisplayMemberPath="Name" 
      SelectedItem="{Binding SelectedItemValet, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True"/>

In the ViewModel

valetTypes = GetValueForValet();
public ObservableCollection<Valet> ValetType
{
    get { return valetTypes; }
    set { valetTypes = value; NotifyPropertyChanged("ValetType"); }
}

public Valet SelectedItemValet
{
    get { return selectedItemValet;}
    set { selectedItemValet = value; NotifyPropertyChanged("SelectedItemValet"); }
}

One of the problems I face is that when I do not change the combo box value it binds null, otherwise it binds. I set IsSynchronizedWithCurrentItem as true it tells a Selector should keep the SelectedItem synchronized with the current item. But would not work. How could I do this? I am new to WPF MVVM.

Upvotes: 0

Views: 687

Answers (2)

Pikoh
Pikoh

Reputation: 7713

You´ve got one problem in your code:

public ValetServices SelectedItemValet
{
    get { return selectedItemValet;}
    set { selectedItemValet = value; NotifyPropertyChanged("SelectedItemValet"); }
}

ValetType is Type Valet, but SelectedItemValet is Type ValetServices. They should match. After changing that, to select the first item for example, do this:

valetTypes = GetValueForValet();
this.SelectedItemValet=ValetType.FirstOrDefault(); 

Upvotes: 2

Tom C.
Tom C.

Reputation: 603

The easy solution would be to provide a default value to your SelectedItemValet.

In some method of your ViewModel, that is called when you ViewModel is initialized (typically the constructor) you can set SelectedItemValet to the value you want

Upvotes: 2

Related Questions