The following example fills the ItemsControl with a List of BackupDirectories which I get from code.
How can I change this
I love Richard Nienaber's answer, but as Chuu pointed out, it really doesn't tell how to accomplish what Richard is refering to as a solution. Therefore I have chosen to provide you with the way I ended up doing this, ending with the result Richard is talking about.
In this case I'm creating a greeting widget that needs to know which options it has to greet in. This may be an over-engineered solution to OPs question as I am also creating an container for possible future widgets.
First I set up my collection to handle the different greetings
public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }
public GreetingElement this[int index]
{
get
{
return base.BaseGet(index) as GreetingElement;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new GreetingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((GreetingElement)element).Greeting;
}
}
Then we create the acutal greeting element and it's interface
(You can omit the interface, that's just the way I'm always doing it.)
public interface IGreeting
{
string Greeting { get; set; }
}
public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
[ConfigurationProperty("greeting", IsRequired = true)]
public string Greeting
{
get { return (string)this["greeting"]; }
set { this["greeting"] = value; }
}
}
The greetingWidget property so our config understands the collection
We define our collection GreetingWidgetCollection
as the ConfigurationProperty
greetingWidget
so that we can use "greetingWidget" as our container in the resulting XML.
public class Widgets : System.Configuration.ConfigurationSection
{
public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;
[ConfigurationProperty("greetingWidget", IsRequired = true)]
public GreetingWidgetCollection GreetingWidget
{
get { return (GreetingWidgetCollection) this["greetingWidget"]; }
set { this["greetingWidget"] = value; }
}
}
The resulting XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<widgets>
<greetingWidget>
<add greeting="Hej" />
<add greeting="Goddag" />
<add greeting="Hello" />
...
<add greeting="Konnichiwa" />
<add greeting="Namaskaar" />
</greetingWidget>
</widgets>
</configuration>
And you would call it like this
List<GreetingElement> greetings = Widgets.GreetingWidget.All;