2016-12-07 1 views
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"); 

が、私はそれを必要とします

これはうまくいきません。

私が必要とするもう1つは、制御値を取得するための同じ機能です。

ありがとうございました。私の作品

答えて

1

ソリューション:

/// <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); 
関連する問題