2
votes

I am making simple mvvm binding with picker field in xamarin.forms. I am following this guide xamarin guide setting a picker's bindings

So I made a model:

public class Operation
{
    public int Number { get; set; }
    public string Name { get; set; }
}

An ViewModel:

private List<Operation> _operations;
public List<Operation> Operations
{
    get { return _operations; }
    set
    {
        _operations = value;
        OnPropertyChanged();
    }
}

and View:

<Picker 
    ItemsSource="{Binding Operations}"
    ItemDisplayBinding="{Binding Number}"
    SelectedItem = "{Binding SelectedOperation}"/>
<Entry x:Name="HelpEntry"
       Text="{Binding SelectedOperation.Name}" />

In the Pickers list items are displayed correctly, but when I Select an item number, then binding inside a Entry is not displayed.

Ouestion is, what am I doing wrong?


By the way.. I am doing this because I need to get an selected Operation's Name as variable in my code-behind section, by using HelpEntry.Text. It's not a smartest way and do u have better idea to do that?

Any help would be much appreciate.

2
First of all use an ObservableCollection instead of List. Does the setter of the SelectedOperation call the OnPropertyChange method?Alex
.. I didn't even made a variable inside view model. Everything is working perfectly now. It would be accepted answer. Thanks Alex!Grzegorz G.

2 Answers

3
votes

Your ViewModel should also contain the SelectedOperation property that should also call the OnPropertyChanged method in its setter.

Also you should consider using ObservableCollection instead of List in you view models.

0
votes

Be sure that your ViewModel implements the INotifyPropertyChanged interface. The way to do this easily is to create a BaseViewModel that implements the interface and then inherit all of your concrete view model classes from this base class.

 public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class MainPageVM : ViewModelBase
{...}