#83 – Collection Syntax for Read-Only Vs. Read-Write Properties
October 3, 2010 Leave a comment
When using the XAML collection syntax for a collection-based property that is read/write, the inclusion of an object element representing the collection object is optional.
E.g. Because FrameworkElement.Resources is read/write, we can list a series of resources using either of the following forms.
<!-- Create new ResourceDictionary, assign to Resources property -->
<Window.Resources>
<ResourceDictionary>
<SolidColorBrush x:Key="redBrush" Color="Red"/>
<SolidColorBrush x:Key="indigoBrush" Color="Indigo"/>
</ResourceDictionary>
</Window.Resources>
<!-- Omit ResourceDictionary, use collection syntax, new resources added to existing collection -->
<Window.Resources>
<SolidColorBrush x:Key="redBrush" Color="Red"/>
<SolidColorBrush x:Key="indigoBrush" Color="Indigo"/>
</Window.Resources>
However, for read-only collection properties, because you can’t create a new instance of the collection and assign it to the property, you must use the collection syntax, omitting the object element for the collection.
<StackPanel.Children>
<!-- Children property is read-only, so we can't include UIElementCollection element here -->
<Button Content="Button" Height="25" Width="50" />
<ComboBox Height="23" Width="120" />
</StackPanel.Children>