Last active
December 11, 2015 14:58
-
-
Save hazzik/4617319 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public interface IStatefulComponent | |
{ | |
StateBag ViewState { get; } | |
} | |
public class ViewStateField | |
{ | |
public static ViewStateField<T> Create<T>(StateBag viewState, string key) | |
{ | |
return new ViewStateField<T>(() => viewState, key); | |
} | |
public static ViewStateField<T> Create<T>(Func<StateBag> viewState, string key) | |
{ | |
return new ViewStateField<T>(viewState, key); | |
} | |
public static ViewStateField<T> Create<T>(IStatefulComponent holder, string key) | |
{ | |
return new ViewStateField<T>(() => holder.ViewState, key); | |
} | |
public static ViewStateField<T> Create<T>(StateBag viewState, string key, T @default) | |
{ | |
return new ViewStateField<T>(() => viewState, key, @default); | |
} | |
public static ViewStateField<T> Create<T>(Func<StateBag> viewState, string key, T @default) | |
{ | |
return new ViewStateField<T>(viewState, key, @default); | |
} | |
public static ViewStateField<T> Create<T>(IStatefulComponent holder, string key, T @default) | |
{ | |
return new ViewStateField<T>(() => holder.ViewState, key, @default); | |
} | |
} | |
public class ViewStateField<T> : ViewStateField | |
{ | |
private readonly Func<StateBag> _viewStateAccessor; | |
private readonly string _key; | |
private readonly T _default; | |
public ViewStateField(Func<StateBag> viewStateAccessor, string key) | |
{ | |
_key = key; | |
_viewStateAccessor = viewStateAccessor; | |
} | |
public ViewStateField(Func<StateBag> viewStateAccessor, string key, T @default) | |
{ | |
_key = key; | |
_default = @default; | |
_viewStateAccessor = viewStateAccessor; | |
} | |
public T Value | |
{ | |
get | |
{ | |
var o = ViewState[_key]; | |
if (ReferenceEquals(o, null)) | |
return _default; | |
return (T) o; | |
} | |
set { ViewState[_key] = value; } | |
} | |
public bool IsDirty | |
{ | |
get { return ViewState.IsItemDirty(_key); } | |
set { ViewState.SetItemDirty(_key, value); } | |
} | |
private StateBag ViewState | |
{ | |
get { return _viewStateAccessor(); } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment