WPF 및 Silverlight에 대한 이름으로 DependencyProperty 가져오기
런타임까지 DependencyProperty를 모르거나 액세스할 수 없는 요소에 대한 바인딩을 만들어야 했던 적이 있습니까?
어떤 이유로든 런타임에 요소의 DependencyProperty를 가져와야 했던 적이 있습니까? 그렇다면 이 코드 조각이 유용할 수 있습니다.
public static DependencyProperty GetDependencyPropertyByName(DependencyObject dependencyObject, string dpName) { return GetDependencyPropertyByName(dependencyObject.GetType(), dpName); } public static DependencyProperty GetDependencyPropertyByName(Type dependencyObjectType, string dpName) { DependencyProperty dp = null; var fieldInfo = dependencyObjectType.GetField(dpName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (fieldInfo != null) { dp = fieldInfo.GetValue(null) as DependencyProperty; } return dp; }
사용법은 간단합니다. 한 가지 방법을 사용하면 종속성 개체 인스턴스와 개체에 대한 DependencyProperty의 문자열 표현을 전달할 수 있습니다. 다른 방법을 사용하면 Type에서 종속성 개체를 가져올 수 있습니다. dpName 매개 변수는 코드 또는 XAML에서 참조하는 속성 이름이 아니라 선언된 DependencyProperty의 전체 이름이라는 점을 기억해야 합니다.
다음 예제를 참조하세요.
var usingInstance = GetDependencyPropertyByName(_button, "ContentProperty"); var usingType = GetDependencyPropertyByName(typeof(Button), "ContentProperty");
여기서 볼 수 있듯이 dpName 매개 변수는 속성 이름(Content)이 아니라 실제 DependencyProperty 이름(ContentProperty)입니다. 이제 DepedencyProperty가 있으므로 속성에 대한 모든 종류의 메타 데이터를 가져올 수 있으며 동적 데이터 바인딩을 만들 수도 있습니다. 도움이 되었기를 바랍니다.