This project has moved. For the latest updates, please go here.

Custom Type Editor for all Property Grid Types

Apr 20, 2012 at 12:01 AM

I'd like to replace the ItemsSource on all members of type Type.

 

This application has a number of member fields of type Type, but I'd like each field to be a combobox with a list of non-abstract subtypes of that type. I've got it working with an explicitly set ItemsSource property attribute, which looks like this:

 

	public class ObjectItemsSource<T> : IItemsSource
	{
		public Microsoft.Windows.Controls.PropertyGrid.Attributes.ItemCollection GetValues()
		{
			Microsoft.Windows.Controls.PropertyGrid.Attributes.ItemCollection typeCollection = new Microsoft.Windows.Controls.PropertyGrid.Attributes.ItemCollection();

			//Collect all the types through reflection
			List<Type> typeList = typeof(T).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(T))).ToList();

			foreach (Type t in typeList)
			{
				if (t.IsAbstract)
					continue;

				T classInstance = (T)Activator.CreateInstance(t);

				typeCollection.Add(classInstance, t.Name);
			}

			return typeCollection;
		}
	}

But, when dealing with complex classes whose members need to have the same behavior (and whose classes reside in another assembly), it defaults to the default behavior for Type (which is a textbox, I believe).

Is there a way for me to replace all fields of type System.Type with a custom editor that does this?

 

Apr 20, 2012 at 1:19 AM

If this custom editor could also affect child PropertyGrids, that'd be nice, too (for instance, the property grids that appear in the CollectionEditor).

Coordinator
Apr 20, 2012 at 8:12 PM

Have you tried to add an EditorDefinition to the PropertyGrid?  The documentation shows an example here.

 

Basically, the idea would be to create a custom editor (e.g. a combo box) that would list all the types you want.

<xctk:PropertyGrid>
   <xctk:PropertyGrid.EditorDefinitions>
      
      <xctk:EditorDefinition TargetType="{x:Type s:Type}">
         <xctk:EditorDefinition.EditorTemplate>
            <DataTemplate>
               <!-- Put your custom editor here -->
            </DataTemplate>
         </xctk:EditorDefinition.EditorTemplate>
      </xctk:EditorDefinition>
      
   </xctk:PropertyGrid.EditorDefinitions>
   
   ...
   
</xctk:PropertyGrid>

Keep in mind that your custom editor's DataContext will be a PropertyItem.  That PropertyItem targets one of your object's property of type Type.

 

I hope this will help you.

Apr 24, 2012 at 12:28 AM

Thanks for the response! I'm working on another part of the project for now, but I'll definitely look into that when I work on the task again. Just wanted to let you know your advice is appreciated =)