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

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

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


通过 WPF 标记获取

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;
            }
        }
    }
}

   
   
  
  
  • 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

通过设计器专用方法获取

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

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

/// <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);

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

参考资料


我的博客会首发于 https://blog.walterlv.com/,而 CSDN 会从其中精选发布,但是一旦发布了就很少更新。

如果在博客看到有任何不懂的内容,欢迎交流。我搭建了 dotnet 职业技术学院 欢迎大家加入。

知识共享许可协议

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

发布了382 篇原创文章 · 获赞 232 · 访问量 47万+

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12051822.html