简体   繁体   中英

How to do a Binding of a SelectValue to the MVVM in a project in UWP?

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

@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. 在此处输入图片说明

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