Skip to content

Instantly share code, notes, and snippets.

@bergerjac
Created March 18, 2012 16:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bergerjac/2076769 to your computer and use it in GitHub Desktop.
Save bergerjac/2076769 to your computer and use it in GitHub Desktop.
LightSwitch: Strong Type FindControl
// Client
using System;
using System.Diagnostics;
using System.Windows.Controls;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public static class ControlHelpers
{
public static void ActOnControl<TControl>(
this Microsoft.LightSwitch.Client.IScreenObject context,
string controlName,
Action<TControl> action)
where TControl : System.Windows.DependencyObject
{
IContentItemProxy proxy = context.FindControl(controlName);
if (proxy == null) { return ; }
proxy.ControlAvailable += (o, e) =>
{
TControl control = e.Control as TControl;
if (control == null) { Debug.WriteLine("Wrong Control type."); return; }
action(control);
};
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Microsoft.LightSwitch;
namespace LightSwitchApplication
{
public partial class ENTITYNew
{
partial void ENTITYNew_InitializeDataWorkspace(List<IDataService> saveChangesTo)
{
this.ENTITYProperty = new ENTITY();
//this.FindControl("DateOf") ... no need for this any more
this.ActOnControl<DatePicker>(
this.ENTITYProperty.GetPropertyName(entity => entity.DateOf),
datePicker => datePicker.DisplayDateEnd = DateTime.Today);
}
// Common
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace LightSwitchApplication
{
public static class Expressions
{
///<summary>Gets a type's property name using an expression.</summary>
public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
PropertyInfo propertyInfo = GetPropertyInfo<T>(expression);
return propertyInfo.Name;
}
///<summary>Gets an object's property name using an expression.</summary>
public static string GetPropertyName<T>(this T t, Expression<Func<T, object>> expression)
{
return GetPropertyName(expression);
}
private static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> expression)
{
var lambda = expression as LambdaExpression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
UnaryExpression unaryExpression = lambda.Body as UnaryExpression;
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
{
memberExpression = lambda.Body as MemberExpression;
}
return memberExpression.Member as PropertyInfo;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment