gpt4 book ai didi

c# - 如何检查依赖对象是否包含依赖属性?

转载 作者:行者123 更新时间:2023-11-30 22:49:24 24 4
gpt4 key购买 nike

本质上,我想要一些简单的反射,其中我有一个任意的 DependencyProperty 作为参数。如果 DependencyProperty 由 PlaneProjection 的/属性定义,我会有一个特例(例如,在 if 语句中)。我已经完成了一些简单的 GetType() fandangling,但没有像 MemberType 这样的预期 setter/getter 。

public void SomeFunc(DependencyProperty dp)
{
// if dp is a dependency property of plane projection, do something
// would maybe look like PlaneProjection.hasProperty(dp)
}

最佳答案

使用扩展方法尝试此代码:

public static class Helpers
{
public static DependencyProperty FindDependencyProperty(this DependencyObject target, string propName)
{
FieldInfo fInfo = target.GetType().GetField(propName, BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);

if (fInfo == null) return null;

return (DependencyProperty)fInfo.GetValue(null);
}

public static bool HasDependencyProperty(this DependencyObject target, string propName)
{
return FindDependencyProperty(target, propName) != null;
}

public static string GetStaticMemberName<TMemb>(Expression<Func<TMemb>> expression)
{
var body = expression.Body as MemberExpression;

if (body == null) throw new ArgumentException("'expression' should be a member expression");

return body.Member.Name;
}
}

用法:

planeProjection1.HasDependecyProperty(
Helpers.GetStaticMemberName(() => PlaneProjection.CenterOfRotationXProperty));

关于c# - 如何检查依赖对象是否包含依赖属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1164193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com