2010-03-08 2 views
3

SL3 검사기가 유효성 검사 메시지를 만들 때 DisplayAttribute의 속성을 자동으로 사용하는 것으로 나타났습니다. 코드를 사용하여 컨트롤의 바인딩에서이 정보를 추출하는 방법에 대한 제안 사항에 관심이 있습니다. 나는 예를 포함 시켰습니다 :코드를 사용하여 ViewModel 바운드 컨트롤에서 System.ComponentModel.DataAnnotations.DisplayAttribute 속성 검색

뷰 모델 코드 :

BindingExpression dataExpression = _firstNameTextBox.GetBindingExpression(TextBox.TextProperty) 
Type dataType = dataExpression.DataItem.GetType(); 
PropertyInfo propInfo = dataType.GetProperty(dataExpression.ParentBinding.Path.Path); 
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault(); 
return (attr == null) ? dataExpression.ParentBinding.Path.Path : attr.Name; 
: 나는 다음 (이 경우 텍스트 상자) 같은 일을 컨트롤별로에이를 수있어

[Display(Name="First Name")] 
public string FirstName { get; set; } 

컨트롤의 특정 유형을 알 필요없이 일반적으로이를 수행 할 수있는 방법이 있으면 관심이 있습니다.

미리 감사드립니다.

답변

1

좋은 질문입니다. 불행히도 몇 가지 속성을 하드 코딩하고 매우 안전 할지라도 일반적으로 그렇게 할 방법이 없습니다. 예를 들어 ContentControl.ContentProperty, TextBlock.TextProperty, TextBox.TextProperty 등

Silverlight의 DataForm도 마찬가지입니다. 또한 GetPropertyByPath라는 간단한 도우미 메서드를 다시 구현했습니다. 기본적으로 코드가 수행하는 작업은 다중 단계 속성 경로를 탐색 할 수 있다는 것입니다. 인덱싱 된 속성에는 액세스 할 수 없지만 DataForm도 마찬가지이므로 적어도 그렇게 좋은 것입니다.

그 시점부터, DisplayAttribute를 얻는 것은 당신이 보여준 것과 같습니다.

public static PropertyInfo GetPropertyByPath(object obj, string propertyPath) 
{ 

    ParameterValidation.ThrowIfNullOrWhitespace(propertyPath, "propertyPath"); 

    if (obj == null) { 
     return null; 
    } // if 

    Type type = obj.GetType(); 

    PropertyInfo propertyInfo = null; 
    foreach (var part in propertyPath.Split(new char[] { '.' })) { 

     // On subsequent iterations use the type of the property 
     if (propertyInfo != null) { 
      type = propertyInfo.PropertyType; 
     } // if 

     // Get the property at this part 
     propertyInfo = type.GetProperty(part); 

     // Not found 
     if (propertyInfo == null) { 
      return null; 
     } // if 

     // Can't navigate into indexer 
     if (propertyInfo.GetIndexParameters().Length > 0) { 
      return null; 
     } // if 

    } // foreach 

    return propertyInfo; 

} 
+0

+1 - 나는 최근에 비슷한 것을 거의 비슷하게 작성했습니다. 내가 제안 할 수있는 한 가지는 첨부 된 속성을 처리해야하는 경우 위 코드가 작동하지 않는다는 것입니다 ((Validation.Errors) 등의 괄호를 처리해야 함). – JerKimball

+0

좋은 지적입니다. 인덱스 된 속성 외에도 기본적으로 모든 DataForm 시도 인 일반적인 점선 경로를 처리 할 수 ​​없다는 점을 잊어 버렸습니다. 일반적으로 ViewModel 속성에 액세스하기 때문에 대부분 괜찮습니다. – Josh

+0

아, 다중 단계 속성을 잊어 버렸습니다. 발췌 해 주셔서 감사합니다. 매우 도움이됩니다. – Patrick

관련 문제