它的工作原理:
label1.SetProperty(() => label1.Text, "xxx");
,但我还需要它也可以在其他事情上工作,例如:
checkBox4.SetProperty(() => checkBox4.Checked, true);
那是行不通的
我需要的第二件事是获得控制值的功能。感谢您的建议。
对我有用的解决方案:
/// <summary>
/// Gets control property. Usage: label1.GetProperty2(() => label1.Text);
/// </summary>
public static object GetProperty2<TResult>(this Control @this, Expression<Func<TResult>> property)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
return @this.GetType().GetProperty(propertyInfo.Name, propertyInfo.PropertyType).GetValue(@this, null);
}
/// <summary>
/// Sets control property. Usage: label1.SetProperty2(() => label1.Text, "Zadej cestu k modelu.");
/// </summary>
public static void SetProperty2<TResult>(this Control @this, Expression<Func<TResult>> property, TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertySafeDelegate<TResult>(SetProperty2), new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(propertyInfo.Name, BindingFlags.SetProperty, null, @this, new object[] { value });
}
}
private delegate void SetPropertySafeDelegate<TResult>(Control @this, Expression<Func<TResult>> property, TResult value);