Cela devrait prendre soin de vos besoins en SilverLight:
private static readonly Dictionary<DependencyProperty, Type> _ownerCache = new Dictionary<DependencyProperty, Type>();
// normally you'd use a HashSet<DependencyProperty>, but it's not available in SilverLight
private static readonly Dictionary<Type, Dictionary<DependencyProperty, bool>> _excludeCache = new Dictionary<Type, Dictionary<DependencyProperty, bool>>();
public static bool IsOwnedByTypeOrParent(DependencyProperty dp, Type type)
{
lock (_ownerCache)
{
Type owner;
if (_ownerCache.TryGetValue(dp, out owner))
return owner.IsAssignableFrom(type);
Dictionary<DependencyProperty, bool> exclude;
if (_excludeCache.TryGetValue(type, out exclude))
{
if (exclude.ContainsKey(dp))
return false;
}
FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy);
foreach (FieldInfo field in fields)
{
if (typeof(DependencyProperty).IsAssignableFrom(field.FieldType))
{
try
{
object value = field.GetValue(null);
if (object.ReferenceEquals(dp, value))
{
_ownerCache[dp] = field.DeclaringType;
return true;
}
}
catch
{
}
}
}
if (exclude == null)
{
exclude = new Dictionary<DependencyProperty, bool>();
_excludeCache[type] = exclude;
}
exclude.Add(dp, false);
/* optional if you want to minimize memory overhead. unnecessary unless
* you are using this on enormous numbers of types/DPs
*/
foreach (var item in _excludeCache)
{
item.Value.Remove(dp);
}
return false;
}
}
Bien que surveillez le BindingFlags.FlattenHierarchy si vous voulez seulement Par exemple, il détecte les DP déclarés sur cette classe, comme cela obtient tous les DP hérités, par exemple FrameworkElement – mattmanser
Eh bien, il ne les "obtient" pas, il ne vérifie que tous les champs hérités. "Largeur" et propriétés similaires héritées –
Eh bien, je ne pouvais pas obtenir cela pour travailler avec mon cas.En particulier, je devrais être capable de dire quelque chose comme: P laneProjection pp = new PlaneProjection(); pp.HasDependencyProperty (PlaneProjection.CenterOfRotationXProperty); // ceci a renvoyé null. Cependant, j'ai dû changer l'appel de HasDependencyProperty à FindDependencyProperty (target, prop.GetType(). Name) pour le compiler correctement. – roblocop