View Model Items on ListView Xamarin Forms

Hey today I'll show you how to implement the MVVM pattern to update, add and remove data in a listview on Xamarin Forms.

Here the root project files



  • User.cs : This file contains our user model data in this case Name and Age.
  • UserVM.cs : This file contains all the logic to bind data between view and root model also implements INotifyPropertyChanged pattern.
  • EditUserPage.cs : This is the page to edit user info have two entries and on button to save data.
  • MainPage.cs : This page contains the main listview and a button to add a new user to the listview data we use an ObservableCollection that allow auto-refresh listview data when you modify the datasource, also I implement the listview ContextActions to allow user to modify the listview items with two options edit and delete(iOS swipe left and Android/WP Long click on cell).
Now we have the code for each file:

public class EditUserPage : ContentPage
{
UserVM UserVM {
get{
return this.BindingContext as UserVM;
}
}
Entry UserName { get; set; } = new Entry(){
Placeholder = "Name"
};
Entry UserAge { get; set; } = new Entry(){
Placeholder = "Age",
Keyboard = Keyboard.Numeric
};
Button Savedata { get; set; } = new Button(){
Text = "Save"
};
public EditUserPage (UserVM uservm)
{
BindingContext = uservm;
UserName.SetBinding (Entry.TextProperty, "Name", BindingMode.TwoWay);
UserAge.SetBinding (Entry.TextProperty, "Age", BindingMode.TwoWay);
Savedata.Clicked += Savedata_Clicked;
Content = new StackLayout {
Padding = new Thickness(50,20),
Spacing = 20,
Children = {
UserName,
UserAge,
Savedata
}
};
}
async void Savedata_Clicked (object sender, EventArgs e)
{
await Navigation.PopModalAsync (true);
}
}
view raw EditUserPage.cs hosted with ❤ by GitHub
public class MainPage : ContentPage
{
public ListView ListView { get; set; } = new ListView();
public Button Button { get; set; } = new Button(){
Text = "Add New User"
};
public ObservableCollection<UserVM> ListViewData { get; set; } = new ObservableCollection<UserVM>();
public MainPage ()
{
Title = "ListViewVM Page";
Button.Clicked += Button_Clicked;
ListView.ItemsSource = ListViewData;
ListView.ItemTemplate = new DataTemplate (GetCustomCell);
ListView.ItemTemplate.SetBinding (TextCell.TextProperty, "Name");
ListView.ItemTemplate.SetBinding (TextCell.DetailProperty, "Age");
Content = new StackLayout {
Children = {
Button,
ListView
}
};
}
private Cell GetCustomCell()
{
var cell = new TextCell ();
var editItem = new MenuItem () {
Text = "Edit"
};
editItem.Clicked += EditItem_Clicked;
editItem.SetBinding (MenuItem.CommandParameterProperty, ".");
cell.ContextActions.Add(editItem);
var deleteItem = new MenuItem () {
Text = "Delete",
IsDestructive = true
};
deleteItem.SetBinding (MenuItem.CommandParameterProperty, ".");
deleteItem.Clicked += DeleteItem_Clicked;
cell.ContextActions.Add(deleteItem);
return cell;
}
void DeleteItem_Clicked (object sender, EventArgs e)
{
var userItem = (sender as MenuItem).CommandParameter as UserVM;
ListViewData.Remove (userItem);
}
async void EditItem_Clicked (object sender, EventArgs e)
{
var userItem = (sender as MenuItem).CommandParameter as UserVM;
await Navigation.PushModalAsync (new EditUserPage(userItem));
}
async void Button_Clicked (object sender, EventArgs e)
{
var userItem = new UserVM(new User());
ListViewData.Add (userItem);
await Navigation.PushModalAsync (new EditUserPage(userItem));
}
}
view raw MainPage.cs hosted with ❤ by GitHub
public class User
{
public string Name { get; set; } = string.Empty;
public int Age { get; set; } = 0;
public User ()
{
}
}
view raw User.cs hosted with ❤ by GitHub
public class UserVM:INotifyPropertyChanged
{
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
if (PropertyChanged != null) {
PropertyChanged (this, new PropertyChangedEventArgs (property));
}
}
#endregion
private User User { get; set; }
public string Name
{
get{
return User.Name;
}set{
User.Name = value;
OnPropertyChanged (nameof(Name));
}
}
public int Age
{
get{
return User.Age;
}set{
User.Age = value;
OnPropertyChanged (nameof(Age));
}
}
public UserVM (User @user)
{
User = @user;
}
}
view raw UserVM.cs hosted with ❤ by GitHub

Here the result:





If you want to have access to full example go to this link https://github.com/AlejandroRuiz/XamarinFormsViewModel happy code also if you have doubts plea let me know via comments

Comentarios

Entradas populares