简体   繁体   中英

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.

在此处输入图片说明

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.

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

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(); 

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