<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lesnikowski Blog &#187; WPF</title>
	<atom:link href="http://www.lesnikowski.com/blog/tag/wpf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lesnikowski.com/blog</link>
	<description>EMAIL IMAP POP3 SMTP FTP FTPS barcode components blog</description>
	<lastBuildDate>Fri, 03 Feb 2012 19:20:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>INotifyPropertyChanged with custom targets</title>
		<link>http://www.lesnikowski.com/blog/inotifypropertychanged-with-custom-targets/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-custom-targets</link>
		<comments>http://www.lesnikowski.com/blog/inotifypropertychanged-with-custom-targets/#comments</comments>
		<pubDate>Tue, 24 May 2011 08:47:57 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=1822</guid>
		<description><![CDATA[Wouldn&#8217;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&#8217;s how to do it [...]]]></description>
			<content:encoded><![CDATA[<p>Wouldn&#8217;t it be nice to have a simple attribute instead of backing field madness in Silverlight/WPF? Just like this:</p>
<pre class="brush: csharp;">
public class MainViewModel : ViewModelBase
{
    [NotifyPropertyChanged]
    public string Title { get; set; }
}
</pre>
<p>You can use <a href="http://www.lesnikowski.com/blog/inotifypropertychanged-with-postsharp/"> PostSharp for that</a>, you should at least <a href="http://www.lesnikowski.com/blog/inotifypropertychanged-with-lambdas/">use lambda expressions instead of strings</a>.</p>
<p>Here&#8217;s how to do it without 3rd party software:</p>
<p>1.<br />
In your project <strong>declare base view model</strong>:</p>
<pre class="brush: csharp;">
public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>2.<br />
<strong>Declare the attribute</strong> </p>
<p>It will be used to mark properties that should raise the PropertyChanged event. </p>
<pre class="brush: csharp;">
[AttributeUsage(AttributeTargets.Property)]
public class NotifyPropertyChangedAttribute : Attribute
{
}
</pre>
<p>3.<br />
Create <strong>new MSBuildTasks library project</strong> (it can be in different solution)</p>
<p>Add references to:</p>
<ul>
<li>Mono.Cecil.dll</li>
<li>Mono.Cecil.Pdb.dll (this needed so Cecil can updated pdb file, which is need for debugging the modified assembly)</li>
<li>MSBuild assemblies</li>
</ul>
<p>4.<br />
<strong>Create new MSBuild task</strong></p>
<p>It will inject PropertyChanged event invocation on properties marked with NotifyPropertyChanged attribute.</p>
<pre class="brush: csharp;">
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(&quot;NotifyPropertyChanged&quot;))
                        {
                            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(
                    &quot;RaisePropertyChanged method was not found in type &quot;
                    + 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 == &quot;RaisePropertyChanged&quot;
                    &amp;&amp; method.Parameters.Count == 1
                    &amp;&amp; method.Parameters[0].ParameterType.FullName
                        == &quot;System.String&quot;)
                {
                    return method;
                }
            }
            if (type.BaseType.FullName == &quot;System.Object&quot;)
                return null;
            return FindRaisePropertyChangedMethod(
                type.BaseType.Resolve());
        }

        [Required]
        public string AssemblyPath { get; set; }
    }
}
</pre>
<p>5.<br />
<strong>Compile the task assembly</strong>, </p>
<p>and copy it to &#8220;$(SolutionDir)..libMSBuildMSBuildTasks.dll&#8221; folder along with Mono.Cecil.dll and Mono.Cecil.Pdb.dll assemblies.</p>
<p>4.<br />
Finally <strong>modify your Silverlight/WPF project (.csproj file)</strong>:</p>
<pre class="brush: xml;">
&lt;Project&gt;
  ...
  &lt;UsingTask TaskName=&quot;MSBuildTasks.NotifyPropertyChangedTask&quot; AssemblyFile=&quot;$(SolutionDir)..libMSBuildMSBuildTasks.dll&quot; /&gt;
  &lt;Target Name=&quot;AfterCompile&quot;&gt;
    &lt;MSBuildTasks.NotifyPropertyChangedTask AssemblyPath=&quot;$(ProjectDir)obj$(Configuration)$(TargetFileName)&quot; /&gt;
  &lt;/Target&gt;
&lt;/Project&gt;
</pre>
<p>Voila! Enjoy!</p>
<p>Here&#8217;s the source code of the MSBuildTasks project:<br />
<a href='http://www.lesnikowski.com/blog/wp-content/uploads/2011/05/MSBuildTasks.zip'>MSBuildTasks</a></p>
<p>Most ideas in this blog post are those of <a href="http://www.marcinobel.com/">Marcin Obel</a> but he&#8217;s to lazy to write a blog post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/inotifypropertychanged-with-custom-targets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with lambdas</title>
		<link>http://www.lesnikowski.com/blog/inotifypropertychanged-with-lambdas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-lambdas</link>
		<comments>http://www.lesnikowski.com/blog/inotifypropertychanged-with-lambdas/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 21:48:22 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=475</guid>
		<description><![CDATA[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 { [...]]]></description>
			<content:encoded><![CDATA[<p>There are several ways of implementing <em>INotifyPropertyChanged</em> in WPF applications.</p>
<p>One that I particularly like is by using <a href="http://www.lesnikowski.com/blog/inotifypropertychanged-with-postsharp/">PostSharp to implement INotifyPropertyChanged</a>.</p>
<p>If you are not comfortable with PostSharp you can at least get rid of those nasty strings in standard implementation:</p>
<pre class="brush: csharp;">
public class Model : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(&quot;Status&quot;);
        }
    }
};
</pre>
<p>Labda expressions look nicer and are easier to refactor:</p>
<pre class="brush: csharp;">
public class MyModel : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(() =&gt; Status);
        }
    }
};
</pre>
<p>First thing we need to do is to create base class for all our ViewModels:</p>
<pre class="brush: csharp;">
public class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(
        Expression&lt;Func&lt;object&gt;&gt; expression)
    {
        string propertyName = PropertyName.For(expression);
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>The implementation of PropertyName.For is very straightforward: <a href="http://www.lesnikowski.com/blog/property-name-from-lambda/">How to get property name from lambda</a>.</p>
<p>That&#8217;s it!<br />
Nice, easy to refactor, compile-time checked <em>INotifyPropertyChanged</em> implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/inotifypropertychanged-with-lambdas/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>M-V-VM talk</title>
		<link>http://www.lesnikowski.com/blog/m-v-vm-talk/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=m-v-vm-talk</link>
		<comments>http://www.lesnikowski.com/blog/m-v-vm-talk/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 08:49:58 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=184</guid>
		<description><![CDATA[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]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/10/thumbnail.jpeg" alt="thumbnail" title="thumbnail" width="256" height="192" class="alignleft size-full wp-image-185" /><br />
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.</p>
<p><a href='http://www.lesnikowski.com/blog/wp-content/uploads/2009/10/MVVM_Presentation.pptx'>MVVM_Presentation</a><br />
<a href='http://www.lesnikowski.com/blog/wp-content/uploads/2009/10/MyMVVMSample.zip'>MyMVVMSample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/m-v-vm-talk/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with PostSharp 1.5</title>
		<link>http://www.lesnikowski.com/blog/inotifypropertychanged-with-postsharp/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-postsharp</link>
		<comments>http://www.lesnikowski.com/blog/inotifypropertychanged-with-postsharp/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 12:03:01 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=14</guid>
		<description><![CDATA[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(&#34;Message&#34;); } } // ... } PostSharp is a great tool to [...]]]></description>
			<content:encoded><![CDATA[<p>If you are doing WPF development, most likely you are tired of writing property implementations that raise <em>PropertyChanged</em> event manually:</p>
<pre class="brush: csharp;">
public class MainWindowViewModel : ViewModel
{
    private string _message;

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

    // ...
}
</pre>
<p><a href="http://www.postsharp.org">PostSharp</a> is a great tool to make such things simplier.</p>
<p>Let&#8217;s look at the specific ViewModel class that has a <em>Message</em> property that is <strong>bound to some UI element</strong> using XAML:</p>
<pre class="brush: csharp;">
public class MainWindowViewModel : ViewModel
{
    [RaisePropertyChanged]
    public string Message { get; set; }

    // ...
}
</pre>
<p> Notice the <em>RaisePropertyChanged</em> attribute, which we&#8217;ll implement later.</p>
<p>Here&#8217;s our <strong>base ViewModel</strong> class that provides <strong>actual implementation</strong> of the <em>INotifyPropertyChanged</em> interface:</p>
<pre class="brush: csharp;">
public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>Finally the PostSharp attribute:</p>
<pre class="brush: csharp;">
[Serializable]  // required by PostSharp
public class RaisePropertyChangedAttribute : OnMethodBoundaryAspect
{
    private string _propertyName;

    /// &lt;summary&gt;
    /// Executed at runtime, after the method.
    /// &lt;/summary&gt;
    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&quot;set_&quot;, &quot;&quot;);
    }

    private static bool IsPropertySetter(MethodBase method)
    {
        return method.Name.StartsWith(&quot;set_&quot;);
    }
};
</pre>
<p>Note that we are validating if the method is in fact a property only during <strong>compilation time</strong> using <em>CompileTimeValidate</em> method.</p>
<p>During compile time appropriate invocations of <em>OnPropertyChanged</em> method will be <strong>injected after every set operation</strong> applied to the <em>Message</em> property.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/inotifypropertychanged-with-postsharp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

