#83 – Collection Syntax for Read-Only Vs. Read-Write Properties

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>
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: