Keith

Keith

  • NA
  • 6
  • 0

PropertyGrid with ConfigurationElementCollection (cannot Add / Remove from collection)

Aug 13 2010 12:01 PM
I have a ConfigurationElementCollection bound to a PropertyGrid.

The Collection properties can be viewed successful and each existing item can actually be edited without problem.

However, I cannot Add new items or Remove existing ones as the Add/Remove buttons are disabled.

There are public Add() and Remove() methods on the Collection and also a public Indexer which I thought would be sufficient.

Is there anything obvious I'm missing here.

Code is shown below:
 public class WatchConfiguration : ConfigurationSection
{

public WatchConfiguration()
{

}

public static WatchConfiguration Current
{
get
{
return (WatchConfiguration)ConfigurationManager.GetSection("WatchConfiguration");
}
}

[ConfigurationProperty("Watches", IsDefaultCollection = false), ConfigurationCollection(typeof(WatchCollection), AddItemName = "addWatch", ClearItemsName = "clearWatches", RemoveItemName = "removeWatch")]
public WatchCollection Watches
{
get { return this["Watches"] as WatchCollection; }
set { (this["Watches"] as WatchCollection).Add(new WatchElement()); }
}

public override bool IsReadOnly()
{
return false;
}

}



public class WatchCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.AddRemoveClearMap;
}
}

public WatchElement this[int index]
{
get { return (WatchElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
BaseRemoveAt(index);
BaseAdd(index, value);
}
}

public void Add(WatchElement element)
{
BaseAdd(element);
}

public void Clear()
{
BaseClear();
}

protected override ConfigurationElement CreateNewElement()
{
return new WatchElement();
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((WatchElement)element).Epic;
}

public void Remove(WatchElement element)
{
BaseRemove(element.Epic);
}

public void Remove(string epic)
{
BaseRemove(epic);
}

public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
}




public class WatchElement : ConfigurationElement
{
public WatchElement() { }

public WatchElement(string epic, string colour)
{
this.Epic = epic;
this.Colour = colour;
}

public override bool IsReadOnly()
{
return false;
}

[ConfigurationProperty("Epic", IsRequired = true, DefaultValue = "")]
public string Epic
{
get { return (string)this["Epic"]; }
set { this["Epic"] = value; }
}

[ConfigurationProperty("Colour", IsRequired = true, DefaultValue = "No description.")]
public string Colour
{
get { return (string)this["Colour"]; }
set { this["Colour"] = value; }
}

public Color GetColour()
{
return Color.FromName(this.Colour);
}
}

The PropertyGrid is actually bound to the WatchConfiguration class.

Any help would be greatly appreciated!!!