|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Mvvm3_Basic.Model;
namespace Mvvm3_Basic.ViewModel
{
public class ContactViewModel : INotifyPropertyChanged
{
public ContactViewModel()
{
AddCommand = new MyCommand<object>(OnAdd);
SaveCommand = new MyCommand<object>(OnSave);
UpdateCommand = new MyCommand<object>(OnUpdate);
DeleteCommand = new MyCommand<object>(OnDelete);
GetCommand = new MyCommand<object>(GetContact);
}
public ObservableCollection<Contact> Contacts { get; set; }
public MyCommand<object> AddCommand { get; set; }
public MyCommand<object> SaveCommand { get; set; }
public MyCommand<object> UpdateCommand { get; set; }
public MyCommand<object> DeleteCommand { get; set; }
public MyCommand<object> GetCommand { get; set; }
void OnAdd(object obj)
{
Contact c = new Contact { Name = string.Empty, Email = string.Empty };
SelectedContact = c;
PropertyChanged(this, new PropertyChangedEventArgs("SelectedContact"));
Debug.WriteLine("Add Called!");
}
void OnSave(object obj)
{
db.Save(SelectedContact);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedContact"));
Debug.WriteLine("Save Called!");
}
void OnUpdate(object obj)
{
db.Update(SelectedContact);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Contacts"));
Debug.WriteLine("Update Called!");
}
void OnDelete(object obj)
{
db.Delete(SelectedContact);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedContact"));
Debug.WriteLine("Delete Called!");
}
void GetContact(object obj)
{
if (Contacts == null) Contacts = new ObservableCollection<Contact>();
Contacts.Clear();
db.GetContactList();
Contacts = db.contactlist;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Contacts"));
Debug.WriteLine("Refresh called!");
}
DB db = new DB(); //at class level
private Contact _ctc = new Contact();
public Contact SelectedContact
{
get { return _ctc; }
set
{
_ctc = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedContact"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MyCommand<T> : ICommand
{
readonly Action<T> callback;
public MyCommand(Action<T> callback)
{
this.callback = callback;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (callback != null) { callback((T)parameter); }
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.