2012-07-02 5 views
0

다른 개발자가 작성한 많은 사용자 정의 개체에 속성 표를 바인딩했습니다. 이러한 객체는 지속적으로 변경 및 업데이트되므로 NotImplemented 예외을 던지는 속성을 포함합니다. 때때로 그들은 [(true "로 다른 일을 얻는 대신 사용 꼬추") 폐기]propertyGrid가 특정 속성에 바인딩하지 못하도록합니다.

대신 다른 개발자 성가신의

같은 속성을 포함한다. 내가 아는 것들은 나중에 바뀔 것이다. 내 속성 그리드가 특정 속성을 손상시키지 않도록하려면 어떻게해야합니까?

도움 주셔서 감사합니다. 다른 개발자들은 그것을 높이 평가합니다;)

답변

1

디자이너가 아닌 런타임에 PropertyGrid를 객체에 바인딩하려고합니다. winform 디자이너에서 propertygrid를 의미하는 경우 대답이 달라 지므로 ControlDesigner의 postFilterEvents 메서드를 살펴 봐야합니다.

가장 간단한 해결책은 숨기려는 속성에 대해 BrowsableAttribute를 false로 설정하는 것입니다. 즉, 다른 개발자가 ObsoleteAttribute를 추가하면 [Browsable(false)]도 추가해야합니다. 그러나 나는 당신이 뭔가 더 "자동"을 원한다는 것을 이해합니다. PropertyGrid에 전달하기 전에 개체의 속성에 대한 찾아보기 가능한 속성을 변경하는 메서드를 작성할 수 있습니다. 이것은 각 속성에 대해 TypeDescriptor를 가져 와서 BrowsableAttribute를 가져오고 ObsoleteAttribute가 있다는 사실에 따라 값을 설정하거나 예외를 throw하는 방식으로 수행 할 수 있습니다 (이 경우 브라우저를 비공개로 설정하여 리플렉션을 통해 수행해야합니다) . 코드는 다음과 같을 수 있습니다.

private static void FilterProperties(object objToEdit) 
    { 
     Type t = objToEdit.GetType(); 
     PropertyInfo[] props = t.GetProperties(); 
     // create fooObj in order to have another instance to test for NotImplemented exceptions 
     // (I do not know whether your getters could have side effects that you prefer to avoid) 
     object fooObj = Activator.CreateInstance(t); 
     foreach (PropertyInfo pi in props) 
     { 
      bool filter = false; 
      object[] atts = pi.GetCustomAttributes(typeof(ObsoleteAttribute), true); 
      if (atts.Length > 0) 
       filter = true; 
      else 
      { 
       try 
       { 
        object tmp = pi.GetValue(fooObj, null); 
       } 
       catch 
       { 
        filter = true; 
       } 
      } 
      PropertyDescriptor pd = TypeDescriptor.GetProperties(t)[pi.Name]; 
      BrowsableAttribute bAtt = (BrowsableAttribute)pd.Attributes[typeof(BrowsableAttribute)]; 
      FieldInfo fi = bAtt.GetType().GetField("browsable", 
           System.Reflection.BindingFlags.NonPublic | 
           System.Reflection.BindingFlags.Instance); 
      fi.SetValue(bAtt, !filter); 
     } 
    } 

이 코드는 작동하지만 한계가 있습니다. 편집중인 클래스에는 최소한 BrowsableAttribute가 있어야합니다 (true 또는 false로 설정되어 있어도 상관 없습니다). 그렇지 않으면 PropertyGrid는 항상 비어 있습니다.

관련 문제