Last active
June 3, 2016 04:53
-
-
Save srakowski/52e1207f15200b5ea547a63f6d45ebe7 to your computer and use it in GitHub Desktop.
Example of Dynamic Proxy ViewModel in C#?
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
using System; | |
namespace VMSandbox | |
{ | |
class AModel | |
{ | |
public DateTime Date { get; set; } = DateTime.UtcNow; | |
public int MyLifeForTheCodeDownloads { get; set; } = Int32.MaxValue; | |
} | |
} |
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
namespace VMSandbox | |
{ | |
class AModelViewModel : ViewModelBase | |
{ | |
private AModel _subject = new AModel(); | |
protected override object Subject | |
{ | |
get | |
{ | |
return _subject; | |
} | |
} | |
public string Date | |
{ | |
get { return _subject.Date.ToShortDateString(); } | |
} | |
} | |
} |
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
using System; | |
namespace VMSandbox | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
dynamic vm = new AModelViewModel(); | |
Console.WriteLine(vm.Date); | |
Console.WriteLine(vm.MyLifeForTheCodeDownloads); | |
} | |
} | |
} |
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
using System.Dynamic; | |
namespace VMSandbox | |
{ | |
abstract class ViewModelBase : DynamicObject | |
{ | |
abstract protected object Subject { get; } | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
result = null; | |
var property = Subject.GetType().GetProperty(binder.Name); | |
if (property == null) | |
return false; | |
result = property.GetValue(Subject).ToString(); | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment