"Linda Liu [MSFT]" <v-****@online.mic rosoft.comwrote in message
news:MU******** ******@TK2MSFTN GHUB02.phx.gbl. ..
Hi Ben,
Thank you very much for your sharing!
I'm interested in your solution, but I couldn't understand it fully.
If possible, could you please give us a complete sample code?
Thank you for your time!
Something like this (not compile tested, but at least 99% there):
internal class MissingAccessor s<T{
static T PropertyNotGett able(object that) { throw new
NotSupportedExc eption(); }
static void PropertyNotSett able(object that, T value) { throw new
NotSupportedExc eption(); }
}
public class ArbitraryProper tyProxy<mContro lType, mFieldType>
{
public delegate mFieldType PropertyGetter( mControlType that);
public delegate void PropertySetter( mControlType that, mFieldType
value);
public readonly PropertyGetter getFrom;
public readonly PropertySetter setOnto;
public ArbitraryProper tyProxy(Propert yInfo pi)
{
if (pi.PropertyTyp e != mFieldType) throw new ArgumentExcepti on();
try {
getFrom =
(PropertyGetter )Delegate.Creat eDelegate(typeo f(PropertyGette r),
pi.GetGetMethod ());
}
catch {
getFrom = MissingAccessor s<mFieldType>.P ropertyNotGetta ble;
}
try {
setOnto =
(PropertySetter )Delegate.Creat eDelegate(typeo f(PropertySette r),
pi.GetSetMethod ());
}
catch {
getFrom = MissingAccessor s<mFieldType>.P ropertyNotSetta ble;
}
}
}
public class PropertyLateBin der<mControlTyp e, mFieldType>
{
private readonly static Dictionary<stri ng,
ArbitraryProper tyProxy<mContro lType, mFieldType>cach edProps = new
Dictionary<stri ng, ArbitraryProper tyProxy<mContro lType, mFieldType>>();
public static ArbitraryProper tyProxy<mContro lType, mFieldType>
BindProperty(st ring propName)
{
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy ;
if (!cachedProps.T ryGetValue(prop Name, out proxy)) {
try {
PropertyInfo pi =
typeof(mControl Type).GetProper ty(propName);
if (pi != null)
proxy = new ArbitraryProper tyProxy<mContro lType,
mFieldType>(pi) ;
}
catch {}
cachedProps[propName] = proxy;
}
return proxy;
}
public static mFieldType Get(mControlTyp e instance, string propName) {
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy =
BindProperty(pr opName);
if (proxy == null) throw new ArgumentExcepti on("propName") ;
return proxy.getFrom(i nstance);
}
public static void Set(mControlTyp e instance, string propName,
mFieldType newValue) {
ArbitraryProper tyProxy<mContro lType, mFieldTypeproxy =
BindProperty(pr opName);
if (proxy == null) throw new ArgumentExcepti on("propName") ;
proxy.setOnto(i nstance, value);
}
}
void ChangeColor(For m f, Color c, string whichColor) {
foreach (Control c in f.Controls)
PropertyLateBin der<Control, Color>.Set(c, whichColor, c);
}
ChangeColor(thi s, Color.Black, "BackColor" );
ChangeColor(thi s, Color.Red, "ForeColor" );
Imagine that whichColor could be a dropdown list or something like that, so
it's not feasible to do early binding.