1
我有一個控制參數設置到另一個線程的代碼:C#設置/獲取到/的控件的屬性從另一個線程
private delegate void SetPropertySafeDelegate<TResult>(System.Windows.Forms.Control @this, Expression<Func<TResult>> property, TResult value);
public static void SetProperty<TResult>(this System.Windows.Forms.Control @this, Expression<Func<TResult>> property, TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null || [email protected]().IsSubclassOf(propertyInfo.ReflectedType) || @this.GetType().GetProperty(propertyInfo.Name, propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertySafeDelegate<TResult>(SetProperty), new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(propertyInfo.Name, BindingFlags.SetProperty, null, @this, new object[] { value });
}
}
它的工作原理是這樣的:
label1.SetProperty(() => label1.Text, "xxx");
,但我需要它也可以在其他方面工作,如:
checkBox4.SetProperty(() => checkBox4.Checked, true);
哪個不起作用。
我需要的第二件事是獲得控制值的相同功能。
非常感謝您的建議。