Posts Tagged ‘WPF’

INotifyPropertyChanged with custom targets

Tuesday, May 24th, 2011

Wouldn’t it be nice to have a simple attribute instead of backing field madness in Silverlight/WPF? Just like this:

public class MainViewModel : ViewModelBase
{
    [NotifyPropertyChanged]
    public string Title { get; set; }
}

You can use PostSharp for that, you should at least use lambda expressions instead of strings.

Here’s how to do it without 3rd party software:

1.
In your project declare base view model:

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};

2.
Declare the attribute

It will be used to mark properties that should raise the PropertyChanged event.

[AttributeUsage(AttributeTargets.Property)]
public class NotifyPropertyChangedAttribute : Attribute
{
}

3.
Create new MSBuildTasks library project (it can be in different solution)

Add references to:

  • Mono.Cecil.dll
  • Mono.Cecil.Pdb.dll (this needed so Cecil can updated pdb file, which is need for debugging the modified assembly)
  • MSBuild assemblies

4.
Create new MSBuild task

It will inject PropertyChanged event invocation on properties marked with NotifyPropertyChanged attribute.

using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace MSBuildTasks
{
    public class NotifyPropertyChangedTask : Task
    {
        public override bool Execute()
        {
            InjectMsil();
            return true;
        }

        private void InjectMsil()
        {
            var assemblyDefinition = AssemblyDefinition.ReadAssembly(
                AssemblyPath,
                new ReaderParameters { ReadSymbols = true });

            var module = assemblyDefinition.MainModule;

            foreach (var type in module.Types)
            {
                foreach (var prop in type.Properties)
                {
                    foreach (var attribute in prop.CustomAttributes)
                    {
                        string fullName = attribute.Constructor.DeclaringType.FullName;
                        if (fullName.Contains("NotifyPropertyChanged"))
                        {
                            InjectMsilInner(module, type, prop);
                        }
                    }
                }
            }
            assemblyDefinition.Write(
                this.AssemblyPath,
                new WriterParameters { WriteSymbols = true });
        }

        private static void InjectMsilInner(
            ModuleDefinition module,
            TypeDefinition type,
            PropertyDefinition prop)
        {
            var msilWorker = prop.SetMethod.Body.GetILProcessor();
            var ldarg0 = msilWorker.Create(OpCodes.Ldarg_0);

            MethodDefinition raisePropertyChangedMethod =
                FindRaisePropertyChangedMethod(type);
            if (raisePropertyChangedMethod == null)
                throw new Exception(
                    "RaisePropertyChanged method was not found in type "
                    + type.FullName);

            var raisePropertyChanged = module.Import(
                raisePropertyChangedMethod);
            var propertyName = msilWorker.Create(
                OpCodes.Ldstr,
                prop.Name);
            var callRaisePropertyChanged = msilWorker.Create(
                OpCodes.Callvirt,
                raisePropertyChanged);

            msilWorker.InsertBefore(
                prop.SetMethod.Body.Instructions[
                    prop.SetMethod.Body.Instructions.Count - 1],
                ldarg0);

            msilWorker.InsertAfter(ldarg0, propertyName);
            msilWorker.InsertAfter(
                propertyName,
                callRaisePropertyChanged);
        }

        private static MethodDefinition FindRaisePropertyChangedMethod(
            TypeDefinition type)
        {
            foreach (var method in type.Methods)
            {
                if (method.Name == "RaisePropertyChanged"
                    &&  method.Parameters.Count == 1
                    &&  method.Parameters[0].ParameterType.FullName
                        == "System.String")
                {
                    return method;
                }
            }
            if (type.BaseType.FullName == "System.Object")
                return null;
            return FindRaisePropertyChangedMethod(
                type.BaseType.Resolve());
        }

        [Required]
        public string AssemblyPath { get; set; }
    }
}

5.
Compile the task assembly,

and copy it to “$(SolutionDir)/../lib/MSBuild/MSBuildTasks.dll” folder along with Mono.Cecil.dll and Mono.Cecil.Pdb.dll assemblies.

4.
Finally modify your Silverlight/WPF project (.csproj file):

<project>
  ...
  <usingTask TaskName="MSBuildTasks.NotifyPropertyChangedTask" AssemblyFile="$(SolutionDir)..libMSBuildMSBuildTasks.dll" />
  <target Name="AfterCompile">
    <msbuildTasks.NotifyPropertyChangedTask AssemblyPath="$(ProjectDir)obj$(Configuration)$(TargetFileName)" />
  </target>
</project>

Voila! Enjoy!

Here’s the source code of the MSBuildTasks project:
MSBuildTasks

INotifyPropertyChanged with lambdas

Tuesday, February 16th, 2010

There are several ways of implementing INotifyPropertyChanged in WPF applications.

One that I particularly like is by using PostSharp to implement INotifyPropertyChanged.

If you are not comfortable with PostSharp you can at least get rid of those nasty strings in standard implementation:

public class Model : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged("Status");
        }
    }
};

Labda expressions look nicer and are easier to refactor:

public class MyModel : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(() => Status);
        }
    }
};

First thing we need to do is to create base class for all our ViewModels:

public class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(
        Expression<func<object>> expression)
    {
        string propertyName = PropertyName.For(expression);
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};

The implementation of PropertyName.For is very straightforward: How to get property name from lambda.

That’s it!
Nice, easy to refactor, compile-time checked INotifyPropertyChanged implementation.

M-V-VM talk

Tuesday, October 13th, 2009

thumbnail
Here are the slide-show and code from my recent M-V-VM talk on the Warsaw .NET group. I was talking about different flavors of MVVM, blendability, unit testing and separation of concerns. All in all, I think it was a good talk with great audience participation.

MVVM_Presentation
MyMVVMSample

INotifyPropertyChanged with PostSharp 1.5

Tuesday, September 15th, 2009

If you are doing WPF development, most likely you are tired of writing property implementations that raise PropertyChanged event manually:

public class MainWindowViewModel : ViewModel
{
    private string _message;

    public string Message
    {
        get
        {
            return _message;
        }
        set
        {
            _message = value;
            OnPropertyChanged("Message");
        }
    }

    // ...
}

PostSharp is a great tool to make such things simplier.

Let’s look at the specific ViewModel class that has a Message property that is bound to some UI element using XAML:

public class MainWindowViewModel : ViewModel
{
    [RaisePropertyChanged]
    public string Message { get; set; }

    // ...
}

Notice the RaisePropertyChanged attribute, which we’ll implement later.

Here’s our base ViewModel class that provides actual implementation of the INotifyPropertyChanged interface:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
    }
};

Finally the PostSharp attribute:

[Serializable]  // required by PostSharp
public class RaisePropertyChangedAttribute : OnMethodBoundaryAspect
{
    private string _propertyName;

    /// <summary>
    /// Executed at runtime, after the method.
    /// </summary>
    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
        ViewModel viewModel = (ViewModel)eventArgs.Instance;
        viewModel.OnPropertyChanged(_propertyName);
    }

    public override bool CompileTimeValidate(MethodBase method)
    {
        if (IsPropertySetter(method))
        {
            _propertyName = GetPropertyName(method);
            return true;
        }
        return false;
    }

    private static string GetPropertyName(MethodBase method)
    {
        return method.Name.Replace"set_", "");
    }

    private static bool IsPropertySetter(MethodBase method)
    {
        return method.Name.StartsWith("set_");
    }
};

Note that we are validating if the method is in fact a property only during compilation time using CompileTimeValidate method.

During compile time appropriate invocations of OnPropertyChanged method will be injected after every set operation applied to the Message property.