#75 – Sometimes You Must Use Property Element Syntax

In many cases, you can set a property value in XAML using a string value, even though the property being set is a more complex object.  (E.g. Setting Background property to new instance of SolidColorBrush just by indicating color of brush as a string).

But there are cases when the property that you want to set cannot be set using a simple string.  In these cases, you must use the property element syntax.

As an example, you can have a context menu pop up when a button is right-clicked by setting the button’s ContextMenu property.  A context menu can not be described using only a string value, so you must use property element syntax:

<Button Name="btnClick" Content="Click Me" Height="23" Width="75">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Open"/>
            <MenuItem Header="Save"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>
Advertisements

#74 – Property Element Syntax

The simplest way to set property values in XAML is by using attributes.

<Button Content="Click Me" Height="23" Width="75" Background="Red" />

Because the Button.Background property is of type Brush, the string “Red” is actually used to create a new instance of a SolidColorBrush (subtype of Brush), with its Color property set to an RGB value of FF,00,00 (entirely red).

You can also set a property value using property element syntax.  This syntax allows setting a property value using an embedded XAML element of the form TypeName.PropertyName.

You typically use property element syntax for property values that can’t be expressed as strings.

Using the property element syntax, we can set the button’s background to a red brush as follows:

<Button Name="btnClick" Content="Click Me" Height="23" Width="75" Click="Button_Click">
    <Button.Background>
        <SolidColorBrush Color="Red"/>
    </Button.Background>
  </Button>