Weaving properties

The PropertyChanged.Fody plugin for Fody already supports Catel out of the box, but only for property change notifications. However, with the Catel.Fody plugin, it is possible to automatically weave a simple property into a Catel property.

The following property definition:

public string Name { get; set; }

will be weaved into:

public string Name
{
    get { return GetValue<string>(NameProperty); }
    set { SetValue(NameProperty, value); }
}

public static readonly PropertyData NameProperty = RegisterProperty("Name", typeof(string));

In the background, Catel.Fody will handle the following workflow:

  •  Find all types in the assembly deriving from ModelBase (thus also ViewModelBase)
  • Check if the type has an automatic property backing field (only those properties are weaved)
  • Add the PropertyData field for the property
  • Instantiate the PropertyData field in the static constructor of the type
  • Replace the content of the getter and setter with the appropriate calls to GetValue and SetValue

Automatically excluded properties

By default, Catel.Fody ignores the following properties and types by default because they shouldn't be weaved:

  • All properties of type ICommand
  • Properties without an automatically generated backing field

Specifying default values for weaved properties

By default, Catel uses null as default values for reference types. For value types, it will use default(T). To specify the default value of a weaved property, use the DefaultValue attribute as shown in the example below:

public class Person : ModelBase
{
    [DefaultValue("Geert")]
    public string FirstName { get; set; }
 
    public string LastName { get; set; }
}

This will be weaved into:

public class Person : ModelBase
{
  	public string FirstName
	{
		get { return GetValue<string>(FirstNameProperty); }
		set { SetValue(FirstNameProperty, value); }
	}

	public static readonly PropertyData FirstNameProperty = RegisterProperty("FirstName", typeof(string), "Geert");

	public string LastName
	{
		get { return GetValue<string>(LastNameProperty); }
		set { SetValue(LastNameProperty, value); }
	}

	public static readonly PropertyData LastNameProperty = RegisterProperty("LastName", typeof(string), null);
}

How to get automatic change notifications

So, the Fody plugin for Catel automatically searches for the On[PropertyName]Changed methods. If a method is found, it will automatically be called when the property has changed. For example, the OnNameChanged is automatically called when the Name property is changed in the example below:

public string Name { get; set; }

private void OnNameChanged()
{
    // this method is automatically called when the Name property changes
}