WPF Property Grid - PullRequest
       21

WPF Property Grid

1 голос
/ 06 декабря 2010

Есть ли способ при привязке к классу объекта зависимости скрывать свойства класса?Я имею в виду эти «Диспетчер», «DependencyObjectType» и «IsSealed»?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;

namespace WPGDemoApp
{

   public class SampleObject : DependencyObject
   {
      readonly static DependencyProperty IdProperty = DependencyProperty.Register("ID", typeof(int), typeof(SampleObject));


      public int ID
      {
         get { return (int)GetValue(IdProperty); }
         set
         {
            SetValue(IdProperty, value);
         }
      }
      public string Name
      {
         get { return "Leeroy Jenkins"; }
      }
   }
}

Ответы [ 2 ]

1 голос
/ 07 декабря 2010

Джесси, ваш вопрос не очень понятен, но если я правильно понимаю, вы просто хотите показать свойства, имеющиеся в вашем SampleObject, то есть те, которые добавлены вами, а не те, которые унаследованы от его базового класса.

1. проверьте, как ваш PropertyGrid получает свойства выбранного объекта -

он должен извлекать свойства выбранного типа объектов, а не для самого объекта -

Type type = this.SelectedItem.GetType();

properties =TypeDescriptor.GetProperties(type);

вместо -

properties = TypeDescriptor.GetProperties(this.SelectedItem);

2. Если это не решит проблему или если вы хотите больше контроля над тем, какие свойства показывать в вашей PG, то вы можете создать пользовательский атрибут,Чтобы добиться этого, я создал собственный атрибут (аналогично IsBrowsable), вам просто нужно украсить ваше свойство этим атрибутом и изменить реализацию Property Grid, чтобы соблюдать его.

Вот класс атрибута -

/// <summary>
/// Attribute to identify the Custom Proeprties.
/// Only Proeprties marked with this attribute(true) will be displayed in property grid.
/// </summary>
[global::System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class IsCustomPropertyAttribute : Attribute
{
    // See the attribute guidelines at 
    //  http://go.microsoft.com/fwlink/?LinkId=85236

    private bool isCustomProperty;

    public static readonly IsCustomPropertyAttribute Default = new IsCustomPropertyAttribute(false);
    public static readonly IsCustomPropertyAttribute No = new IsCustomPropertyAttribute(false);
    public static readonly IsCustomPropertyAttribute Yes = new IsCustomPropertyAttribute(true);

    /// <summary>
    /// Initializes a new instance of the <see cref="IsCustomPropertyAttribute"/> class.
    /// </summary>
    /// <param name="isCustomProperty">if set to <c>true</c> [is RT display property].</param>
    public IsCustomPropertyAttribute(bool isCustomProperty)
    {
        this.isCustomProperty = isCustomProperty;
    }

    /// <summary>
    /// Gets a value indicating whether this instance is RT display property.
    /// </summary>
    /// <value>
    ///     <c>true</c> if this instance is RT display property; otherwise, <c>false</c>.
    ///     The default is false.
    /// </value>
    public bool IsCustomProperty
    {
        get { return isCustomProperty; }
        set { isCustomProperty = value; }
    }

    /// <summary>
    /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
    /// </summary>
    /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
    /// <returns>
    ///     <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
    /// </returns>
    public override bool Equals(object obj)
    {
        IsCustomPropertyAttribute attribute = obj as IsCustomPropertyAttribute;
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        return attribute.isCustomProperty == isCustomProperty;
    }

    public override int GetHashCode()
    {
        return isCustomProperty.GetHashCode();
    }

    public override bool IsDefaultAttribute()
    {
        return isCustomProperty == IsCustomPropertyAttribute.Default.isCustomProperty;
    }
}

В сетке свойств добавьте флажок перед добавлением свойства в сетку.как то так -

// Gets the attributes for the property.
AttributeCollection attributes = propertyDescriptor.Attributes;

//Checks to see if the value of the IsCustomPropertyAttribute is Yes.
IsCustomPropertyAttribute myAttribute = 
(IsCustomPropertyAttribute)attributes[typeof(IsCustomPropertyAttribute)];

//Check if current property is CustomProperty or not
if (myAttribute.IsCustomProperty == true)
{
    AddProperty(propertyDescriptor);
}
0 голосов
/ 09 марта 2012

Это работало для расширяемых объектов, которые были объектами зависимости.Я только что создал простой атрибут маркера под названием ViewablePropertyAttribute.Я не хотел, чтобы все объекты зависимости были доступны в сетке.

    public class EllevateExpandableObjectConverter : ExpandableObjectConverter
{
    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext   context, object value, Attribute[] attributes)
    {
        var propertyDescriptors =  
            base.GetProperties(context, value, attributes.OfType<ViewablePropertyAttribute>().Cast<Attribute>().ToArray());

        var result = propertyDescriptors.Cast<PropertyDescriptor>()
            .Where(pd => pd.Attributes.OfType<ViewablePropertyAttribute>().Any())
            .ToArray();

        return new PropertyDescriptorCollection(result);
    }
}

[ViewablePropertyAttribute]
[TypeConverter(typeof(EllevateExpandableObjectConverter)]
public MyComplexType MyInstance {get;set; }
...