Skip to content

Code Behind Fields

Code inspections to verify declarations and usages of x:Name defined fields

Introduction

In XAML, we can use the x:Name directive to declare a code-behind field for the XAML element is applied to.

Consider the following code:

<ContentPage>
  <Label x:Name="myLabel" Text="Hello World"/>
</ContentPage>

The Label element will have a code behind field named myLabel generated by the XAML design tools. We can then use this field (myLabel) in our code behind class or reference it within the current XAML document via the x:Reference expression.

There are various issues that can arise from using the x:Name directive and MFractor inspects for many known issues and provides code-fixes to resolve them.

x:Name Has Invalid Characters

As an x:Name directive declares a new code-behind field, it's value must follow C#'s identifier name restrictions. If we do not follow these restrictions, our code will not compile.

If we enter an invalid name, MFractor will detect this and add a code error to inform you the x:Name value will cause a compilation error:

Invalid code behind field name detection

Duplicate Code Behind Field Declarations

MFractor will inspect all x:Name directives and validate that they are unique within the document. As the x:Name directive creates a new code-behind field, duplicate x:Name values will also create duplicate fields with the same name, causing a C# compiler error.

Duplicate code behind field name detection

Empty Code Behind Field Declaration

MFractor will inspect all x:Name directives and validate that they have a value; excluding a value from the x:Name attribute will generate a compiler error:

Empty code behind field declaration

Verify Referenced Code Behind Field Exists

We can use the x:Reference expression to retrieve the instance of a code-behind field declared via the x:Name directive. This is commonly usedto set BindingContext of an element to another control in the visual tree, enabling us to data-bind to a property on that control.

For example:

<Switch x:Name="switch" />

<Label BindingContext="{x:Reference switch}"
        IsVisible="{Binding IsToggled}"
        Text="Hello World!"/>

In the above example, we are control the visibility of the Label through the IsToggled property on the Switch.

MFractor will inspect usages of the x:Reference expression and verify that the referenced element is defined in the current document using x:Name:

Empty code behind field declaration

If the referenced code behind field name closely matches a known x:Name value, MFractor will suggest a code fix to autocorrect the typo to this name.

Comments