Question

I got the following code :

public class PluginShape : INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            RaisePropertyChanged("Name");
        }
    }

    #region Implement INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

public class SpeedGenerator : PluginShape
{
    private int _SpeedValue;
    public int SpeedValue
    {
        get { return _SpeedValue; }
        set
        {
            _SpeedValue = value;
            RaisePropertyChanged("SpeedValue");
        }
    }

    public SpeedGenerator()
    {
        Name = "DefaultName";
    }
}

Then I'd like to filter the properties so that I only get the SpeedValue property. I thought the following code will be ok, but it doesn't work :

var props = obj.GetType().GetProperties();
var filteredProps = obj.GetType().GetProperties(BindingFlags.DeclaredOnly);

in "props" I got both SpeedValue and Name properties but in "filteredProps" I got nothing... Any help please ?

Was it helpful?

Solution

According to the documentation,

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

Specify BindingFlags.Public to include public properties in the search.

Thus, the following should do what you want:

var filteredProps = obj.GetType().GetProperties(BindingFlags.Instance | 
                                                BindingFlags.Public |
                                                BindingFlags.DeclaredOnly);

OTHER TIPS

Once you start passing BindingFlags, you need to specify exactly what you want.

Add BindingFlags.Instance | BindingFlags.Public.

You could provide a custom Attribute for properties you'd like to use and query on those. I used this way to only have certain properties being displayed in as ListView Properties.

 [AttributeUsage(AttributeTargets.Property)]
 public class ClassAttribute : Attribute
 {
   public String PropertyName;
   public String PropertyDescription;
 }
// Property declaration
[ClassAttribute(PropertyName = "Name", PropertyDescription = "Name")]
public String Name { get; private set; }

// Enumeration
  IEnumerable<PropertyInfo> PropertyInfos = t.GetProperties();
  foreach (PropertyInfo PropertyInfo in PropertyInfos)
  {
    if (PropertyInfo.GetCustomAttributes(true).Count() > 0)
    {
      PropertyInfo info = t.GetProperty(PropertyInfo.Name);
     }
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top