Created
February 24, 2011 19:12
-
-
Save jgable/842689 to your computer and use it in GitHub Desktop.
CheckedItemCollection for wrapping a collection of checkable items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.ObjectModel; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System; | |
/// <summary> | |
/// A collection of checked items. | |
/// </summary> | |
/// <typeparam name="TItem">The type of the item.</typeparam> | |
public class CheckedItemCollection<TItem> : ObservableCollection<CheckedItemWrapper<TItem>> | |
{ | |
public CheckedItemCollection() | |
: base() | |
{ | |
} | |
public CheckedItemCollection(IEnumerable<TItem> items) | |
: base(items.Select(x => new CheckedItemWrapper<TItem>(x))) | |
{ | |
} | |
public List<TItem> CheckedItems | |
{ | |
get | |
{ | |
return this.Items == null ? new List<TItem>() | |
: this.Items.Where(x => x.Checked) | |
.Select(y => y.Item) | |
.ToList(); | |
} | |
} | |
public void Add(TItem item) | |
{ | |
this.Add(new CheckedItemWrapper<TItem>(item)); | |
} | |
public void CheckAll() | |
{ | |
SetChecked(true); | |
} | |
public void UncheckAll() | |
{ | |
SetChecked(false); | |
} | |
public void CheckWhere(Predicate<TItem> filterAction, bool unCheckAllFirst = false) | |
{ | |
if (unCheckAllFirst) | |
UncheckAll(); | |
SetChecked(true, this.Items.Where(x => filterAction(x.Item))); | |
} | |
public void UnCheckWhere(Predicate<TItem> filterAction, bool unCheckAllFirst = false) | |
{ | |
if (unCheckAllFirst) | |
UncheckAll(); | |
SetChecked(false, this.Items.Where(x => filterAction(x.Item))); | |
} | |
private void SetChecked(bool isChecked, IEnumerable<CheckedItemWrapper<TItem>> items = null) | |
{ | |
if (items == null) | |
items = this.Items; | |
foreach (var item in items) | |
{ | |
if (item.Checked != isChecked) | |
item.Checked = isChecked; | |
} | |
} | |
} | |
public class CheckedItemWrapper<TItem> : MVVM4u2.Common.ViewModelBase | |
{ | |
private bool chk; | |
public bool Checked | |
{ | |
get { return chk; } | |
set | |
{ | |
if (chk != value) | |
{ | |
chk = value; | |
OnPropertyChanged("Checked"); | |
} | |
} | |
} | |
private TItem item; | |
public TItem Item | |
{ | |
get { return item; } | |
set | |
{ | |
item = value; | |
OnPropertyChanged("Item"); | |
} | |
} | |
public CheckedItemWrapper() | |
: this(default(TItem)) | |
{ | |
} | |
public CheckedItemWrapper(TItem item) | |
{ | |
this.Item = item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment