I often use a ViewModel class that contains a collection of Contacts and allows me to iterated through the collection with Previous and Next buttons.
I find that I've got duplicate versions of this class all over the place and I'd like to make my code reusable.
How would I go about making the following code reusable (i've been going round in circles for a while now):
public class PartiesViewModel : BaseViewModel
{
const int MaxParties = 20;
public ObservableCollection<Party> Parties { get; set; }
public PartiesViewModel(ObservableCollection<Party> parties)
{
Parties = parties;
Party = Parties.FirstOrCreateIfEmpty();
Party.PropertyChanged += UpdatePartyShortNamesList;
Parties.CollectionChanged += Parties_CollectionChanged;
ClearCommand = new RelayCommand(ClearPressed, CanClear);
NextCommand = new RelayCommand(NextPressed, CanPressNext);
PrevCommand = new RelayCommand(PrevPressed, CanPressPrev);
}
void UpdatePartyShortNamesList(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "ShortName")
NotifyPropertyChanged("PartyShortNames");
}
void Parties_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NotifyPropertyChanged("PartyNames");
NotifyPropertyChanged("PartyShortNames");
NotifyPropertyChanged("Count");
}
Party _Party;
public Party Party
{
get { return _Party; }
set
{
_Party = value;
NotifyPropertyChanged("Party");
NotifyPropertyChanged("Count");
}
}
public string Count
{
get
{
var list = Parties.ToList();
list.RemoveAll(x => x.IsEmpty());
int current = list.FindIndex(x => x == Party) + 1;
int count = list.Count();
if (current == 0)
return string.Format("{0} of {0}", count + 1);
else
return string.Format("{0} of {1}", current, count);
}
}
public RelayCommand PrevCommand { get; set; }
public bool CanPressPrev() { return IndexOf(Party) > 0; }
public void PrevPressed()
{
try
{
int i = IndexOf(Party);
Party = Parties[i - 1];
}
catch (Exception ex) { Message.ShowError(ex); }
}
public RelayCommand NextCommand { get; set; }
public bool CanPressNext() { return !Party.IsNullOrEmpty() && IndexOf(Party) != MaxParties; }
public void NextPressed()
{
try
{
if (IndexOf(Party) + 1 == Parties.Count)
{
Party = new Party();
Parties.Add(Party);
}
else
{
int i = IndexOf(Party);
Party = Parties[i + 1];
}
}
catch (Exception ex) { Message.ShowError(ex); }
}
public RelayCommand ClearCommand { get; set; }
public bool CanClear()
{
return !Party.IsNullOrEmpty();
}
public void ClearPressed()
{
try
{
int i = IndexOf(Party);
if (Party == Parties.Last())
Party.Clear();
else
{
Parties.RemoveAll(x => x == Party);
Party = Parties[i];
}
}
catch (Exception ex) { Message.ShowError(ex); }
}
int IndexOf(Party party) { return Parties.ToList().FindIndex(x => x == party); }
public static List<string> PartyTypes { get { return new List<string>() { "Individual", "Company", "Partnership" }; } }
public bool IsCompany { get; set; }
}