0

I've been trying to capture the SelectValue of a comboBox in the ViewModel but I could not.

This is my code

<ComboBox SelectedValue="{Binding TipoDoc, Mode=TwoWay}"/>

this is the ViewModel

private string tipodoc; 
public string TipoDoc 
{ 
    get => tipodoc; 
    set 
    { 
        tipodoc = value; 
        RaisePropertyChanged();
     } 
} 

I could not capture the value of the comboBox.

what am I doing wrong? Thanks

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Wilmilcard
  • 281
  • 4
  • 13
  • You should really read up on binding MVVM and `NotifyPropertyChanged` there are plenty of tutorials around, however this may help you https://stackoverflow.com/questions/19632270/binding-combobox-selecteditem-using-mvvm – TheGeneral Sep 22 '18 at 00:29
  • Did you set ItemsSource in ComboBox?.. – Ashiq Hassan Sep 22 '18 at 03:16

1 Answers1

0

@Ashiq's suggestion was correct. You need to set ItemsSource for the ComboBox.

I made a code sample for your reference:

<Page.DataContext>
    <local:ViewModel></local:ViewModel>
</Page.DataContext>

<Grid>
    <ComboBox ItemsSource="{Binding source}" SelectedValue="{Binding TipoDoc, Mode=TwoWay}"/>
</Grid>
public class ViewModel : INotifyPropertyChanged
{
    private string tipodoc;
    public string TipoDoc
    {
        get => tipodoc;
        set
        {
            tipodoc = value;
            RaisePropertyChanged("TipoDoc");
        }
    }

    public ObservableCollection<string> source { get; set; }

    public ViewModel()
    {
        source = new ObservableCollection<string>();
        source.Add("item1");
        source.Add("item2");
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

Then, when you select one item, the TipoDoc property value will be changed. enter image description here

Xie Steven
  • 8,544
  • 1
  • 9
  • 23