Fody And ReactiveUI
A ReactiveUI Model
If you are using ReactiveUI you binding model probably looks something like the following.
public class Person : ReactiveObject
{
string givenNames;
public string GivenNames
{
get { return givenNames; }
set { this.RaiseAndSetIfChanged(x => x.GivenNames, value); }
}
string familyName;
public string FamilyName
{
get { return familyName; }
set { this.RaiseAndSetIfChanged(x => x.FamilyName, value); }
}
}
Now this is fine. It is strong typed and supports both INotifyPropertyChanging and INotifyPropertyChanged. However using IL Weaving and Fody this code can be simplified.
How to setup Fody
Install the VSIX (Visual Studio Addin)
First off install the Fody VSIX.
Note: this is a once off per machine and only helps you configure Fody for a project. It is not required to build and the resultant project will build on other developers machines and on your build server.
Enable Fody for your proect
Select the target project and use the top level menu
Project > Fody > Configure
Leave the defaults and click OK. The project will re-load.
Note that you now have a FodyWeavers.xml file in your project.
Get some Fody Addins
If you havn't done so already install nuget
Then in your Package Manager Console type
install-package PropertyChanging.Fody
install-package PropertyChanged.Fody
This will get the PropertyChanging and PropertyChanged Fody addins
Tell Fody to use the Addins
Add the following to FodyWeavers.xml.
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
<PropertyChanged EventInvokerNames="raisePropertyChanged"/>
<PropertyChanging EventInvokerNames="raisePropertyChanging"/>
</Weavers>
Note the EventInvokerNames are raisePropertyChanging and raisePropertyChanged to allow the addins to detect what method to call on the base class.
Tweak your model
Now you model can look like this.
public class Person : ReactiveObject
{
public string GivenNames { get; set; }
public string FamilyName { get; set; }
}
What gets compiled
public class Person : ReactiveObject
{
public string FamilyName
{
get { return this.<FamilyName>k__BackingField; }
set
{
if (!string.Equals(this.<FamilyName>k__BackingField, value))
{
base.raisePropertyChanging("FamilyName");
this.<FamilyName>k__BackingField = value;
base.raisePropertyChanged("FamilyName");
}
}
}
public string GivenNames
{
get { return this.<GivenNames>k__BackingField; }
set
{
if (!string.Equals(this.<GivenNames>k__BackingField, value))
{
base.raisePropertyChanging("GivenNames");
this.<GivenNames>k__BackingField = value;
base.raisePropertyChanged("GivenNames");
}
}
}
}
Source code
The source for this post is available here https://github.com/SimonCropp/Experiments/tree/master/FodyReactiveUI
No new comments are allowed on this post.
Comments
No comments yet. Be the first!