Quantcast
Channel: wpftoolkit Discussions Rss Feed
Viewing all articles
Browse latest Browse all 2157

New Post: Put PropertyGrid attributes/interfaces into separate assembly

$
0
0
Unless I'm mistaken about what you're talking about here, it's actually reasonably easy to inject/remove/manipulate attributes in an object you're putting in to a PropertyGrid.

You need to make an ICustomTypeDescriptor in your business layer, and use reflection to run through all of the properties from your object in the model layer. Then for each property you find, create an instance of your custom property descriptor, a class derived from PropertyDescriptor.

For example, in your model layer :
class SomeClass
{
 public string Name
 {
  get;
  set;
 }
}
If you want to get the Name property in to a category called "Some Class Properties" you'd do the following in your business layer:
class SomeClassDescriptor : ICustomTypeDescriptor
{
 SomeClass myInstance;

 public SomeClaseDescriptor( SomeClass anInstance )
 { 
  myInstance = anInstance;
 }
 
 ...
 // You need to implement quite a few methods, but they're relatively simple
 ...

 // Returns the properties you want to edit for your SomeClass instance
 public PropertyDescriptorCollection GetProperties( Attribute[] someAttributes )
 {
  ArrayList properties = new ArrayList();

  PropertyInfo[] objectProperties = myInstance.GetType().GetProperties()
  foreach( PropertyInfo property in objectProperties )
  {
    ArrayList attributeList = new ArrayList();
    attributeList.AddRange( property.GetCustomAttributes(false) );
    
    // Add in your category attribute
    attributeList.Add( new CategoryAttribute("Some Class Properties") );

    // Add in your property descriptor
    Attribute[] attributeArray = (Attribute[])attributeList.ToArray( typeof(Attribute) );
    properties.Add( new SomeClassPropertyDescriptor( property.Name, property, attributeArray );
  }

  // Finally, return your property descriptor collection
  PropertyDescriptor[] propertyArray = (PropertyDescriptor[])properties.ToArray( typeof(PropertyDescriptor) );
  return new PropertyDescriptorCollection( propertyArray );
 }
}
Your SomeClassPropertyDescriptor class needs to be able to set/get the value of the property... but that's easy to do with the PropertyInfo instance.

Hope that helps!

Viewing all articles
Browse latest Browse all 2157

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>