前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >在 WPF 中获取一个依赖对象的所有依赖项属性

在 WPF 中获取一个依赖对象的所有依赖项属性

作者头像
walterlv
发布2023-10-22 10:35:49
发布2023-10-22 10:35:49
4100
举报

本文介绍如何在 WPF 中获取一个依赖对象的所有依赖项属性。


通过 WPF 标记获取

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

public static IEnumerable<DependencyProperty> EnumerateDependencyProperties(object element) { if (element is null) { throw new ArgumentNullException(nameof(element)); } MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element); if (markupObject != null) { foreach (MarkupProperty mp in markupObject.Properties) { if (mp.DependencyProperty != null) { yield return mp.DependencyProperty; } } } } public static IEnumerable<DependencyProperty> EnumerateAttachedProperties(object element) { if (element is null) { throw new ArgumentNullException(nameof(element)); } MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element); if (markupObject != null) { foreach (MarkupProperty mp in markupObject.Properties) { if (mp.IsAttached) { yield return mp.DependencyProperty; } } } }

通过设计器专用方法获取

本来 .NET 中提供了一些专供设计器使用的类型 TypeDescriptor 可以帮助设计器找到一个类型或者组件的所有可以设置的属性,不过我们也可以通过此方法来获取所有可供使用的属性。

下面是带有重载的两个方法,一个传入类型一个传入实例。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

/// <summary> /// 获取一个对象中所有的依赖项属性。 /// </summary> public static IEnumerable<DependencyProperty> GetDependencyProperties(object instance) => TypeDescriptor.GetProperties(instance, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.All) }) .OfType<PropertyDescriptor>() .Select(x => DependencyPropertyDescriptor.FromProperty(x)?.DependencyProperty) .Where(x => x != null); /// <summary> /// 获取一个类型中所有的依赖项属性。 /// </summary> public static IEnumerable<DependencyProperty> GetDependencyProperties(Type type) => TypeDescriptor.GetProperties(type, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.All) }) .OfType<PropertyDescriptor>() .Select(x => DependencyPropertyDescriptor.FromProperty(x)?.DependencyProperty) .Where(x => x != null);


参考资料

本文会经常更新,请阅读原文: https://blog.walterlv.com/post/wpf-get-all-dependency-properties.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 吕毅 (包含链接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 ([email protected])

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-09-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 通过 WPF 标记获取
  • 通过设计器专用方法获取
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档