Created
May 29, 2014 12:59
-
-
Save mrtnkrstn/a8664948f280accf2e85 to your computer and use it in GitHub Desktop.
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; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Collections.Specialized; | |
using CrossUI.Touch.Dialog.Elements; | |
using Cirrious.MvvmCross.Binding.Attributes; | |
using Cirrious.MvvmCross.Binding; | |
using Cirrious.CrossCore.Platform; | |
using Cirrious.CrossCore.WeakSubscription; | |
namespace mrtnkrstn.iOS.Views | |
{ | |
public class MvxBindableSection<TElementTemplate> : Section where TElementTemplate : Element, IBindableElement | |
{ | |
private IEnumerable _itemsSource; | |
private MvxNotifyCollectionChangedEventSubscription _subscription; | |
public MvxBindableSection() : base() | |
{ | |
} | |
public MvxBindableSection(string caption) : base(caption) | |
{ | |
} | |
[MvxSetToNullAfterBinding] | |
public IEnumerable ItemsSource | |
{ | |
get { return _itemsSource; } | |
set { SetItemsSource(value); } | |
} | |
protected virtual void SetItemsSource(IEnumerable value) | |
{ | |
if (_itemsSource == value) { | |
return; | |
} | |
if (_subscription != null) { | |
_subscription.Dispose(); | |
_subscription = null; | |
}; | |
_itemsSource = value; | |
if (_itemsSource != null && !(_itemsSource is IList)) { | |
MvxBindingTrace.Trace (MvxTraceLevel.Warning, | |
"Binding to IEnumerable rather than IList - this can be inefficient, especially for large lists"); | |
} | |
var newObservable = _itemsSource as INotifyCollectionChanged; | |
if (newObservable != null) { | |
_subscription = newObservable.WeakSubscribe (OnItemsSourceCollectionChanged); | |
} | |
NotifyDataSetChanged(); | |
} | |
private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) | |
{ | |
NotifyDataSetChanged(); | |
} | |
private void NotifyDataSetChanged() | |
{ | |
var newElements = new List<Element>(); | |
if (_itemsSource != null) { | |
foreach (var item in _itemsSource) { | |
var element = Activator.CreateInstance<TElementTemplate>(); | |
element.DataContext = item; | |
newElements.Add((Element) element); | |
} | |
} | |
this.RemoveRange (0, Elements.Count); | |
this.AddAll (newElements); | |
var root = this.Parent as RootElement; | |
if (root == null) { | |
root = this.GetImmediateRootElement (); | |
} | |
if (root != null) { | |
var tableView = root.GetContainerTableView (); | |
tableView.ReloadData (); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment