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;
}
使い方は簡単です。 1 つの方法では、依存関係オブジェクトのインスタンスと、オブジェクトの DependencyProperty の文字列表現を渡すことができます。 もう 1 つの方法では、Type から依存関係オブジェクトを取得できます。 最も重要な点は、dpName パラメーターは、コードや XAML で参照するプロパティ名ではなく、宣言されている DependencyProperty の完全な名前であるということです。
次の例を考えてみます。
var usingInstance = GetDependencyPropertyByName(_button, "ContentProperty"); var usingType = GetDependencyPropertyByName(typeof(Button), "ContentProperty");
ご覧のとおり、dpName パラメーターは実際の DependencyProperty 名 (ContentProperty) であり、プロパティ名 (Content) ではありません。 DepedencyProperty が用意できたので、プロパティに関するあらゆる種類のメタデータを取得でき、動的データ バインディングを作成することもできます。 これがお役に立てば幸いです。