提问人:aturnbul 提问时间:8/1/2022 更新时间:8/1/2022 访问量:278
如何在 WinUI 3 中查找有关 DependencyProperty (在 DependencyObject 上) 的 PropertyInfo
How to find PropertyInfo about a DependencyProperty (on a DependencyObject) in WinUI 3
问:
有时,拥有比元数据供应更多的信息很有用。例如,在通用跟踪方法和事件处理程序中,能够在 上找到 的名称(和其他特征)会很有帮助。DependencyProperty
DependencyProperty
DependencyObject
在 WinUI 3 中,我们使用 reports as so 来获取有关对象或类型的所有属性的包含信息(WPF 报告,我们将改用)。System.Reflection
DependencyProperties
MemberType=Properties
GetProperties()
PropertyInfo[]
DependencyProperties
MemberType=Fields
GetFields()
DependencyProperties
实际上声明为字段,并且方法通常默认不列出静态成员。调用时,请务必包含该标志,并在列表中包含 public。static
Get...
Reflection
GetProperties
BindingFlags.Static
BindingFlags.Public
DependencyProperties
接下来,我们检查每个返回的项目,看看它们是否真的与感兴趣的标识符有关。如果包含您感兴趣的标识符并且是您正在检查的项目,请使用该方法查看它们是否都引用相同的标识符(注意:如果 和 位于不同的对象上或标识不同的属性,则为 false)。返回的数组中应该有一个且只有一个匹配项。PropertyInfo[]
DependencyProperty
dp
DependencyProperty
pi
PropertyInfo
object.ReferenceEquals(pi.GetValue(sender), dp)
pi
dp
下面是一个处理程序的开头,它演示:PropertyChanged
private static void BoundPropertyChanged(DependencyObject sender, DependencyProperty dp)
{
// sender is DependencyObject upon which the dp changed
PropertyInfo dpInfo = sender.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
.Where(pi => pi.PropertyType == typeof(DependencyProperty) && object.ReferenceEquals(pi.GetValue(sender), dp)).Single();
// Trace logic, etc.
}
第一个语句有四个部分:
sender.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
获取有关 Sender 类型的所有属性的信息。从本质上讲,该标志意味着也包括继承的属性。BindingFlags.FlattenHierarchy
.Where(pi => pi.PropertyType == typeof(DependencyProperty)
仅选择具有 OF 的成员(路由的事件也可能在 1 的列表中)。PropertyType
DependencyProperty
&& object.ReferenceEquals(pi.GetValue(sender), dp))
进一步将所选项目限制为引用相同标识符的项目。- 该子句选择结果列表中的唯一成员,如果多于(或少于)一个,则引发错误。
.Single();
需要注意的是,这种方法严重依赖于反射,而反射相对较慢。
我不知道有更好的方法,但我欢迎建议和改进!
答: 暂无答案
上一个:从反射中获取的转换列表
评论