Reputation: 1345
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.
Upvotes: 2
Views: 6143
Reputation: 494
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
{...}
Upvotes: 0
Reputation: 3889
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.
Upvotes: 3