【问题标题】:getting custom dependency property获取自定义依赖属性
【发布时间】:2012-05-30 18:58:19
【问题描述】:

我有一个包含我的自定义依赖属性的控件,如下所示:

 public static readonly DependencyProperty MouseEnterColorProperty =
            DependencyProperty.Register("MouseEnterColor", typeof (Color), typeof (SCADAPolyline), new PropertyMetadata(default(Color)));

        public Color MouseEnterColor
        {
            get { return (Color) GetValue(MouseEnterColorProperty); }
            set { SetValue(MouseEnterColorProperty, value); }
        }

这是一个奇怪的问题。我正在使用反射来获取我的属性以设置新值。但是无法获取我的属性。我尝试了 type.GetFields() 的所有可能性

 FieldInfo fieldInfo = type.GetField(name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);

or 

 fieldInfo = type.GetFields(BindingFlags.Static | BindingFlags.Public)
                                          .Where(p => p.FieldType.Equals(typeof(DependencyProperty)) && p.Name==name).FirstOrDefault();

听起来我的财产不见了。我无法访问,这个问题让我很生气。 我怎样才能解决这个问题的任何想法?我正在使用 Silverlight 5.0

【问题讨论】:

  • 你调试过name是什么吗?为什么不尝试获取非静态 MouseEnterColor 包装器?
  • 是的,我检查了它的名字是正确的。
  • +1 以获得良好的描述和代码。总是有帮助:)

标签: silverlight reflection dependency-properties


【解决方案1】:

依赖属性不是字段。它不是通常意义上的类定义的一部分。

在幕后,它存储在依赖属性的集合中。

试试这个例子 from here 作为如何访问它们的指南:

    public static class DependencyObjectHelper
    {
        public static List<DependencyProperty> GetDependencyProperties(Object element)
        {
            List<DependencyProperty> properties = new List<DependencyProperty>();
            MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
            if (markupObject != null)
            {
                foreach (MarkupProperty mp in markupObject.Properties)
                {
                    if (mp.DependencyProperty != null)
                    {
                        properties.Add(mp.DependencyProperty);
                    }
                }
            }

            return properties;
        }

【讨论】:

  • 谢谢。这就是我要找的:)
猜你喜欢
  • 1970-01-01
  • 2013-10-16
  • 2012-08-29
  • 1970-01-01
  • 2011-09-09
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多