<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>Rob's Tech Blog</title>
	
	<link>http://www.robfe.com</link>
	<description>A blog about coding by Rob Fonseca-Ensor</description>
	<lastBuildDate>Thu, 09 May 2013 01:23:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/RFE" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="rfe" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Creating tiled backgrounds in Metro style XAML apps</title>
		<link>http://www.robfe.com/2012/07/creating-tiled-backgrounds-in-metro-style-xaml-apps/</link>
		<comments>http://www.robfe.com/2012/07/creating-tiled-backgrounds-in-metro-style-xaml-apps/#comments</comments>
		<pubDate>Fri, 20 Jul 2012 09:14:01 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Metro]]></category>
		<category><![CDATA[Tile]]></category>
		<category><![CDATA[Tilebrush]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=243</guid>
		<description><![CDATA[TL;DR version: This class will let you tile an image in a Metro-style XAML app. Use an image that&#8217;s at least 128&#215;128 for best memory efficiency Textures can make your application beautiful. Here&#8217;s an example from http://subtlepatterns.com, which is full of classy textures: These textures can make great backgrounds, but because the texture is usually smaller than [...]]]></description>
			<content:encoded><![CDATA[<p><em>TL;DR version: <a title="TileCanvas for Winrt" href="https://gist.github.com/3006848" target="_blank">This class will let you tile an image in a Metro-style XAML app</a>. Use an image that&#8217;s at least 128&#215;128 for best memory efficiency</em></p>
<p>Textures can make your application beautiful. Here&#8217;s an example from <a href="http://subtlepatterns.com/">http://subtlepatterns.com</a>, which is full of classy textures:</p>
<div id="attachment_285" class="wp-caption aligncenter" style="width: 610px"><a href="http://subtlepatterns.com/"><img class="size-full wp-image-285 " style="border: 1px solid black;" title="redox_01" src="http://www.robfe.com/wp-content/uploads/2012/07/redox_01.png" alt="" width="600" height="375" /></a><p class="wp-caption-text">A nice tile texture</p></div>
<p>These textures can make great backgrounds, but because the texture is usually smaller than your application (especially tiny textures like <a href="http://subtlepatterns.com/white-carbonfiber/"><img src="http://subtlepatterns.com/patterns/white_carbonfiber.png" alt="" width="4" height="4" /></a> ), you need to repeat (tile) the image vertically and horizontally. Images that &#8220;match up&#8221; on opposite sides are ideal. All the images on  <a href="http://subtlepatterns.com/">http://subtlepatterns.com</a>, <a href="http://bgrepeat.com/">http://bgrepeat.com</a> and <a href="http://www.repeatxy.com/">http://www.repeatxy.com</a> are tileable.<a href="http://subtlepatterns.com/white-carbonfiber/"><br />
</a></p>
<p>So how do you program your application to repeat this image across a surface? In HTML, you can use the css style &#8220;<a href="http://www.w3schools.com/cssref/pr_background-repeat.asp">background-repeat: repeat</a>&#8221; to tile an image across your webpage. In WPF, you can set up the <a href="http://msdn.microsoft.com/en-us/library/aa970682.aspx">TileBrush properties on an ImageBrush</a> to tile an image across your application. But in Silverlight, Silverlight for Windows Phone, or Metro style XAML applications, you&#8217;re out of luck.</p>
<h1>Fake it</h1>
<p>The easiest solution is to use Photoshop (or cheaper equivalent) to create a huge image that you can set as a background. Just use the pattern tool to tile your texture onto an image that&#8217;s bigger than your application&#8217;s surface will ever be. The question is: can you guarantee a maximum size? With Metro style XAML applications,  <a href="http://blogs.msdn.com/b/b8/archive/2012/03/21/scaling-to-different-screens.aspx">there is no maximum resolution</a>. The other problem is that these massive image files tend to use up a LOT of memory. In my case, it was so much memory that I was likely to fail Microsoft&#8217;s Win8 certification.</p>
<h1>Make it</h1>
<p>There was no way I was going to convert my application into a JavaScript &amp; HTML app, so I set out to create a control that would look just like a WPF tiled brush. The easiest way to do this is to manually arrange a set of images in a control. I&#8217;m very familiar with WPF, and I just knew there&#8217;d be some weird inconsistencies in the new WinRT APIs that made this harder than it should be, so I decided to spike this in WPF first. I inherited from Canvas, gave it an ImageSource property, and slapped my code into the OnRenderSizeChanged method. It worked perfectly, here&#8217;s the code:<br />
<script src="https://gist.github.com/3077863.js?file=TileCanvas.cs"></script><noscript><pre><code class="language-c# c#">    public class TileCanvas : Canvas
    {
        public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register(&quot;ImageSource&quot;, typeof(ImageSource), typeof(TileCanvas), new UIPropertyMetadata(null, OnImageSourceChanged));

        private static void OnImageSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            ((TileCanvas)o).Rebuild();
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            base.OnRenderSizeChanged(sizeInfo);
            Rebuild();
        }

        private void Rebuild()
        {
            if(ImageSource == null)
            {
                return;
            }

            var size = RenderSize;
            Children.Clear();
            var width = (int)ImageSource.Width;
            var height = (int)ImageSource.Height;
            for (int x = 0; x &lt; size.Width; x += width)
            {
                for (int y = 0; y &lt; size.Height; y += height)
                {
                    var image = new Image { Source = ImageSource };
                    Canvas.SetLeft(image, x);
                    Canvas.SetTop(image, y);
                    Children.Add(image);
                }
            }
            Clip = new RectangleGeometry(new Rect(size));
        }
    }
</code></pre></noscript></p>
<h2>I broke a convention <img src='http://www.robfe.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </h2>
<p>If I was a WPF Purist I would have never extended a Panel class in order to provide a visual control. I&#8217;d have built a templated control (Inheriting from Control), and declared the canvas as a template part, and provided a default template that just contained that canvas in my Generic.xaml file. But my whole aim was to keep memory usage low, and in WPF every visual costs you memory, so I decided to pre-optimise. It&#8217;s also simpler this was as I only have to show you one file <img src='http://www.robfe.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<h2>Optimising Memory</h2>
<p>A tilebrush in WPF on a 1000&#215;800 surface will happily repeat a 4 pixel image for you, thousands of times (200,000 to be exact), without breaking a sweat. However, with my TileCanvas, we&#8217;re creating an Image visual every time we want to repeat the tile, so you don&#8217;t want an ImageSource that&#8217;s too small. You have to find a happy balance between a huge image (which uses up a lot of memory by itself) and a lot of small images (where you don&#8217;t keep paying for the image data, but you do pay for the visual tree explosion). I have found that by repeating your pattern, Photoshop style, onto an image that&#8217;s a <strong>sized with a nice round number like 128&#215;128 pixels</strong> is a good compromise. This applies to the WPF spike as well as the following Metro solution.</p>
<h1>Make it &#8211; Metro Style</h1>
<p>If you want to build a Metro Style application, you need to program against the WinRT API. This provides .NET developers with new challenges. Microsoft say that WinRT allows .NET developers to use their existing skills, which is fair. What they don&#8217;t mention is that you&#8217;re going to need a lot of new knowedge. <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230302%28v=vs.110%29.aspx">WinRT is like a parallel universe &#8211; a lot of the things you expect to find are there, but they are a bit different, or they&#8217;re in a different place</a>. A lot of operations are now done asyncronously, which should be make apps snappier. Truly a &#8220;parallel&#8221; universe (sorry).</p>
<p>When I tried to port my WPF TileCanvas over to use the WinRT version of XAML controls, I ran into two differences that changed the way I had to do things:</p>
<ul>
<li>There&#8217;s no longer a RenderSizeChanged method &#8211; after a bit of experimenting, I decided on the LayoutUpdated event (although adding images causes this event to be raised, so I had to track the old size in order to avoid stack overflow)</li>
<li>ImageSources now start with a width and height of 0. It&#8217;s not until the ImageOpened event is raised that you can find out the width and height of an image. And you don&#8217;t get an ImageOpened event until your image is loaded into the Visual Tree. To get around this chicken-and-egg situation, I add a single image to the canvas, and then once it&#8217;s opened and I have the width &amp; height I do a proper layout of the whole screen. I also attach to the ImageFailed event to help you debug, and clean up my event subscriptions once they&#8217;ve fired.</li>
</ul>
<p>Here is my working Metro-style TileCanvas:<br />
<script src="https://gist.github.com/3006848.js?file=TileCanvas.cs"></script><noscript><pre><code class="language-c# c#">    public class TileCanvas : Canvas
    {
        public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register(&quot;ImageSource&quot;, typeof(ImageSource), typeof(TileCanvas), new PropertyMetadata(null, ImageSourceChanged));

        private Size lastActualSize;

        public TileCanvas()
        {
            LayoutUpdated += OnLayoutUpdated;
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        private void OnLayoutUpdated(object sender, object o)
        {
            var newSize = new Size(ActualWidth, ActualHeight);
            if (lastActualSize != newSize)
            {
                lastActualSize = newSize;
                Rebuild();
            }
        }

        private static void ImageSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            TileCanvas self = (TileCanvas)o;
            var src = self.ImageSource;
            if (src != null)
            {
                var image = new Image { Source = src };
                image.ImageOpened += self.ImageOnImageOpened;
                image.ImageFailed += self.ImageOnImageFailed;

                //add it to the visual tree to kick off ImageOpened
                self.Children.Add(image);
            }
        }

        private void ImageOnImageFailed(object sender, ExceptionRoutedEventArgs exceptionRoutedEventArgs)
        {
            var image = (Image)sender;
            image.ImageOpened -= ImageOnImageOpened;
            image.ImageFailed -= ImageOnImageFailed;
            Children.Add(new TextBlock { Text = exceptionRoutedEventArgs.ErrorMessage, Foreground = new SolidColorBrush(Colors.Red) });
        }

        private void ImageOnImageOpened(object sender, RoutedEventArgs routedEventArgs)
        {
            var image = (Image) sender;
            image.ImageOpened -= ImageOnImageOpened;
            image.ImageFailed -= ImageOnImageFailed;
            Rebuild();
        }

        private void Rebuild()
        {
            var bmp = ImageSource as BitmapSource;
            if (bmp == null)
            {
                return;
            }

            var width = bmp.PixelWidth;
            var height = bmp.PixelHeight;

            if(width == 0 || height == 0)
            {
                return;
            }

            Children.Clear();
            for (int x = 0; x &lt; ActualWidth; x += width)
            {
                for (int y = 0; y &lt; ActualHeight; y += height)
                {
                    var image = new Image { Source = ImageSource };
                    Canvas.SetLeft(image, x);
                    Canvas.SetTop(image, y);
                    Children.Add(image);
                }
            }
            Clip = new RectangleGeometry { Rect = new Rect(0, 0, ActualWidth, ActualHeight) };
        }
    }
</code></pre></noscript></p>
<h2>Almost perfect?</h2>
<p>One thing that I would add in future would be to not throw away the entire canvas of images every time it was built. It would be better to determine just how many images need to be added and removed. At the moment, this isn&#8217;t a big issue because metro apps are always fullscreen so they don&#8217;t change size unless you snap/rotate them.</p>
<h2>Shameless plug</h2>
<p>I needed this class because I wanted a background texture in my new Windows 8 game, Chromazone. It&#8217;s just been accepted my Microsoft to the store, check it out: <a href="http://apps.microsoft.com/webpdp/en-US/app/chromazone/fe3aea27-d44f-43e0-8662-1c45178e4dec">http://apps.microsoft.com/webpdp/en-US/app/chromazone/fe3aea27-d44f-43e0-8662-1c45178e4dec</a></p>
<p><a href="http://apps.microsoft.com/webpdp/en-US/app/chromazone/fe3aea27-d44f-43e0-8662-1c45178e4dec"><img class="alignleft size-full wp-image-258" title="Chromazone screenshot" src="http://www.robfe.com/wp-content/uploads/2012/07/afterMove.png" alt="" width="629" height="450" /></a></p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=f-grVIEGoSE:MJIVTE0W4Zs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=f-grVIEGoSE:MJIVTE0W4Zs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=f-grVIEGoSE:MJIVTE0W4Zs:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2012/07/creating-tiled-backgrounds-in-metro-style-xaml-apps/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Building on-the-fly images for WP7 live tiles</title>
		<link>http://www.robfe.com/2012/02/building-on-the-fly-images-for-wp7-live-tiles/</link>
		<comments>http://www.robfe.com/2012/02/building-on-the-fly-images-for-wp7-live-tiles/#comments</comments>
		<pubDate>Tue, 28 Feb 2012 17:06:22 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=230</guid>
		<description><![CDATA[Windows Phone 7.5 (Mango) lets your app create multiple live tiles on the phone&#8217;s start screen (with the ShellTile api). This is a very cool way to provide deep links into your application. It&#8217;s used brilliantly by the the native apps for contacts (you can pin people and see their individual updates), office (you can [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Phone 7.5 (Mango) lets your app create multiple live tiles on the phone&#8217;s start screen (with <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.shell.shelltile(v=vs.92).aspx">the ShellTile api</a>). This is a very cool way to provide deep links into your application. It&#8217;s used brilliantly by the the native apps for contacts (you can pin people and see their individual updates), office (you can pin documents), and music &amp; videos (you can pin albums and playlists).</p>
<p>When you create a new ShellTile, you get to specify one or two image URIs (for the front and back). If you use a relative URI, then the shell will look for the image inside your XAP &#8211; just like any other image URI in your app. But that means you only get to use images that you ship with your app &#8211; how does the music &amp; video app render the album art for each tile? What if you want to take a screenshot of the current game and use that?</p>
<p>One answer is to use or generate images on the internet and use an http-schemed URI, but that approach <a href="http://www.jeff.wilcox.name/2011/09/a-note-about-remote-uris-in-windows-phone-secondary-tiles/">can cause the tile to unpin</a> when you turn off your phone (I don&#8217;t know if that&#8217;s a bug or a feature), and you&#8217;ll also be relying on an internet connection.</p>
<p>The best option is to save the image to your application&#8217;s isolated storage, because you are free to save whatever file you like there (with full control of the content and format), and the image will always be available (so your tile won&#8217;t unpin). If you&#8217;ve already sourced your image from the internet, then you can just save it to iso storage, but what if you want to generate an image on the fly? Have a look at the mail app, and how it tells you how many emails you&#8217;ve got in big letters. If you&#8217;ve got no unread email, it adjusts the position of the email icon too. This image is probably built on the fly by a background process.</p>
<p>But what&#8217;s a good way of rendering text and images to an image file?</p>
<p>In my opinion, the best way to render custom, dynamic content in a Silverlight app is to leverage the platform: just render some XAML. If you create a 173 by 173 control, you&#8217;ve got full control of how those pixels will look. You can even use databinding. You can use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap(v=vs.95).aspx">WriteableBitmap</a>. It&#8217;s got a constructor that takes in a UIElement (which will immediately render that element into the bitmap) and a SaveJpeg extension method that will write the bitmap to a file.</p>
<p>In my <a href="http://www.windowsphone.com/en-US/apps/13d74d49-a2cf-4c6a-94b9-b5fe11b0ece5">Bus Alert London</a> WP7 app, I used this technique to render custom tile icons with maps in the background:</p>
<div id="attachment_237" class="wp-caption alignnone" style="width: 490px"><a href="http://www.robfe.com/wp-content/uploads/2012/02/Colorfultiles.png"><img class="size-full wp-image-237 " title="Bus Alert London" src="http://www.robfe.com/wp-content/uploads/2012/02/Colorfultiles.png" alt="Bus Alert London - Tiles" width="480" height="800" /></a><p class="wp-caption-text">Bus Alert Tiles</p></div>
<p>In the process, I discovered a few very important gotchas:</p>
<ul>
<li>The UIElement that you render has to be in the application&#8217;s visual tree when you call the WriteableBitmap constructor. Otherwise, it may not render at all, may lay out incorrectly, may not have access to the correct StaticResources, or databinding may not occur. You can put it in the visual tree, render it and immediately hide it so that the user never sees it if you like. Unfortunately, this rules out the use of XAML to produce live tiles from background agents.</li>
<li>The image must be stored under the special directory \Shared\ShellContent in your isolated storage folder or it will not be accessible by the operating system.</li>
<li>If you don&#8217;t close the image&#8217;s filestream before creating the live tile you will see a weird bug where the live tile&#8217;s image is only visible when you are moving it around the start screen</li>
<li>If you want transparency, you&#8217;ll need to save a PNG. For this you will need to use the .NET image tools library <a href="http://stackoverflow.com/a/7379297/21433">as documented on stackoverflow</a>.</li>
</ul>
<p>I&#8217;ve also put together a sample project that builds a custom live tile out of XAML and avoids all of these gotchas. It&#8217;s available on the MSDN code gallery at <a href="http://code.msdn.microsoft.com/Building-Dynamic-Live-52bdc195">http://code.msdn.microsoft.com/Building-Dynamic-Live-52bdc195</a></p>
<p>&nbsp;</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=cRAwFZprOVc:Mb1cebRSV-M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=cRAwFZprOVc:Mb1cebRSV-M:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=cRAwFZprOVc:Mb1cebRSV-M:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2012/02/building-on-the-fly-images-for-wp7-live-tiles/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Slides from my Apps World talk: Beginning Windows Phone 7 Development</title>
		<link>http://www.robfe.com/2011/12/slides-from-my-apps-world-talk-beginning-windows-phone-7-development/</link>
		<comments>http://www.robfe.com/2011/12/slides-from-my-apps-world-talk-beginning-windows-phone-7-development/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 09:03:37 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=224</guid>
		<description><![CDATA[I recently gave an entry level talk on Windows Phone 7 development at the Apps World conference in London. If you&#8217;re interested, you can download my slides from here. Some other links that are useful for people who are getting started with WP7 development are: Microsoft&#8217;s AppHub portal (download the SDK, sign up for the developer [...]]]></description>
			<content:encoded><![CDATA[<p>I recently gave an entry level talk on Windows Phone 7 development at the <a href="http://www.apps-world.net/europe/">Apps World conference</a> in London. If you&#8217;re interested, you can download <a href="http://www.robfe.com/wp-content/uploads/2011/12/Windows-Phone-7-Development.pptx">my slides from here</a>.</p>
<p>Some other links that are useful for people who are getting started with WP7 development are:</p>
<ul>
<li><a href="http://create.msdn.com">Microsoft&#8217;s AppHub portal</a> (download the SDK, sign up for the developer program, upload an app)</li>
<li><a href="http://www.jeffblankenburg.com/2011/10/31/31-days-of-mango/">31 days of mango</a> (A set of recipies for the new features in wp7.5 &#8211; mango)</li>
<li><a href="http://www.amazon.com/gp/product/0470912332/">A really great book on windows phone</a>, written by some very handsome authors <img src='http://www.robfe.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </li>
</ul>
<p>&nbsp;</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=aSBVl5irwnM:QiQiVMBYrGs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=aSBVl5irwnM:QiQiVMBYrGs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=aSBVl5irwnM:QiQiVMBYrGs:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2011/12/slides-from-my-apps-world-talk-beginning-windows-phone-7-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Raising the right PropertyChanged with C# 5′s Caller Info Attributes</title>
		<link>http://www.robfe.com/2011/09/raising-the-right-propertychanged-with-c-5s-caller-info-attributes/</link>
		<comments>http://www.robfe.com/2011/09/raising-the-right-propertychanged-with-c-5s-caller-info-attributes/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 09:52:29 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=208</guid>
		<description><![CDATA[Implementing INotifyPropertyChanged typically requires the use of magic strings, and I&#8217;ve never been happy with the various workarounds available. They either affect performance or require a lot of extra developer ceremony (which is no good in big teams). I&#8217;d always been hoping that C# would introduce something similar to the &#8220;typeof&#8221; operator that would help [...]]]></description>
			<content:encoded><![CDATA[<p>Implementing <a title="INPC on MSDN, with a magic string code sample" href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged typically requires the use of magic strings</a>, and I&#8217;ve never been happy with the <a title="Stacktraces" href="http://mvvmlight.codeplex.com/discussions/243955">various</a> <a title="Exppression trees" href="http://michaelsync.net/2009/04/09/silverlightwpf-implementing-propertychanged-with-expression-tree">workarounds</a> <a title="Aspect Oriented Programming" href="http://sachabarber.net/?p=849">available</a>. They either affect performance or require a lot of extra developer ceremony (which is no good in big teams).</p>
<p>I&#8217;d always been hoping that C# would introduce something similar to the &#8220;<a href="http://msdn.microsoft.com/en-us/library/58918ffs.aspx">typeof</a>&#8221; operator that would help you get the name of the current property (or method) without having to use any slow reflection. Before the &#8220;//BUILD/&#8221; conference, I had given up on C# 5 bringing in anything useful here.</p>
<p>But then I was reading <a href="http://blog.functionalfun.net/2011/09/whats-new-in-c-50-and-vbnet.html">Colin Jack&#8217;s summary</a> of the //BUILD/ talk on <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T">Future directions for C# and Visual Basic</a>, and was particularly interested by the new Caller Info Attributes feature of C# 5. This feature is not in the CTP of VS11 yet, so I can&#8217;t test it, but I expect you&#8217;ll be able to write the following RaisePropertyChanged method:</p>
<pre>protected void RaisePropertyChanged([CallerMemberName] string member = "")
{
    var copy = PropertyChanged;
    if(copy != null)
    {
        copy(new PropertyChangedEventArgs(this, member));
    }
}</pre>
<p>and now when you call this method from a property setter, leaving out the optional parameter:</p>
<pre>public string UserName
{
    get
    {
        return _userName;
    }
    set
    {
        _userName=value;
        RaisePropertyChanged();
    }
}</pre>
<p>the compiler will fill out the parameter for you, passing &#8220;UserName&#8221; to the RaisePropertyChanged method.</p>
<p>What I like about this is that the compiler is creating the magic string for you on every compile &#8211; so when you rename your property, the string is automatically kept in sync. This is the best of both worlds, we get the performance benefits of a hardcoded string literal, while keeping everything DRY (and therefore hard to inadvertently break).</p>
<p>&nbsp;</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=J21f8cNTgLo:YrKC8guv4j4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=J21f8cNTgLo:YrKC8guv4j4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=J21f8cNTgLo:YrKC8guv4j4:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2011/09/raising-the-right-propertychanged-with-c-5s-caller-info-attributes/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Design time data nirvana in Blend 4</title>
		<link>http://www.robfe.com/2011/02/design-time-data-nirvana-in-blend-4/</link>
		<comments>http://www.robfe.com/2011/02/design-time-data-nirvana-in-blend-4/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 17:19:31 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Blendability]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=206</guid>
		<description><![CDATA[Quite a few of my posts have been about how to hack design time data into Blend. With Blend 4, you no longer have to hack! The new &#8220;Create Sample Data from Class&#8230;&#8221; option is perfect. Kirupa from the blend team has posted a great writeup on this technique. It works in WPF, Silverlight and [...]]]></description>
			<content:encoded><![CDATA[<p>Quite a few of my posts have been about how to hack design time data into Blend. With Blend 4, you no longer have to hack! The new &#8220;Create Sample Data from Class&#8230;&#8221; option is perfect. <a href="http://www.kirupa.com/windowsphone/creating_sample_data_from_a_class_pg1.htm">Kirupa from the blend team has posted a great writeup on this technique</a>. It works in WPF, Silverlight and WP7. Highly recommended.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=CtfXVqt6Fx0:JsHsngFtAyU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=CtfXVqt6Fx0:JsHsngFtAyU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=CtfXVqt6Fx0:JsHsngFtAyU:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2011/02/design-time-data-nirvana-in-blend-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>There’s a maximum of 255 local messaging channels in Silverlight 4</title>
		<link>http://www.robfe.com/2011/01/maximum-of-255-local-messaging-channels-in-silverlight-4/</link>
		<comments>http://www.robfe.com/2011/01/maximum-of-255-local-messaging-channels-in-silverlight-4/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 22:48:27 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=204</guid>
		<description><![CDATA[Don&#8217;t ask me how I got into this situation, but I found this out the hard way. A quick search will tell you that with Silverlight Local Messaging each message has to be under forty thousand characters, but I haven&#8217;t found anything on the internet yet that tells you that you can have a maximum [...]]]></description>
			<content:encoded><![CDATA[<p>Don&#8217;t ask me how I got into this situation, but I found this out the hard way.</p>
<p>A quick search will tell you that with Silverlight Local Messaging each message <a href="http://msdn.microsoft.com/en-us/library/dd833063(VS.95).aspx#sending_messages_and_receiving_responses"> has to be under forty thousand</a> characters, but I haven&#8217;t found anything on the internet yet that tells you that <strong>you can have a maximum of 255 channels open at a time</strong>. So I&#8217;m taking responsibility and putting it out there.</p>
<p>Going over the limit will give you a cryptic COM exception, and channels can be &#8220;leaked&#8221; if one browser process crashes while another is open (for example iexplore.exe and chrome.exe, or just two instances of chrome.exe). Often closing all browsers will clean up the phantom channels, but not always.</p>
<p>Remember that other Silverlight applications might be using some of these channels too, so you should always design your application such that it uses a minimum number of channels.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=gBuvwDa34A8:R2NDxCvtl7c:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=gBuvwDa34A8:R2NDxCvtl7c:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=gBuvwDa34A8:R2NDxCvtl7c:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2011/01/maximum-of-255-local-messaging-channels-in-silverlight-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introducing Power Assert .NET</title>
		<link>http://www.robfe.com/2010/11/introducing-power-assert-net/</link>
		<comments>http://www.robfe.com/2010/11/introducing-power-assert-net/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 18:22:36 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=199</guid>
		<description><![CDATA[I&#8217;ve just released a new open source project on codeplex: http://powerassert.codeplex.com Power Assert .NET is a .NET port of Groovy&#8217;s PowerAssert, which replaces your normal unit test assertions. Unlike the standard assertions built into nunit, MSTest, and xunit etc; Power Assert gives you a breakdown of all the values within your assertion expression, making it [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released a new open source project on codeplex: <a href="http://powerassert.codeplex.com">http://powerassert.codeplex.com</a></p>
<p>Power Assert .NET is a .NET port of <a href="http://dontmindthelanguage.wordpress.com/2009/12/11/groovy-1-7-power-assert/">Groovy&#8217;s PowerAssert</a>, which replaces your normal unit test assertions.</p>
<p>Unlike the standard assertions built into nunit, MSTest, and xunit etc; Power Assert gives you a breakdown of all the values within your assertion expression, making it quicker for you to hunt down the cause of the test failure:</p>
<p><code>System.Exception : IsTrue failed, expression was:<br />
x + 5 == d.Month * y<br />
| |   |  | |     | |<br />
| |   |  | |     | 6<br />
| |   |  | |     18<br />
| |   |  | 3<br />
| |   |  01/03/2010 00:00:00<br />
| |   False<br />
| 16<br />
11<br />
</code></p>
<p>It&#8217;s quite a simple little thing, but it&#8217;s already saved me lots of debugging time. Give it a go <img src='http://www.robfe.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=Gtp3TidpWsU:K6IxREdO1uk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=Gtp3TidpWsU:K6IxREdO1uk:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=Gtp3TidpWsU:K6IxREdO1uk:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2010/11/introducing-power-assert-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Stream an INotifyPropertyChanged property’s values through an IObservable</title>
		<link>http://www.robfe.com/2010/11/stream-an-inotifypropertychanged-propertys-values-through-an-iobservable/</link>
		<comments>http://www.robfe.com/2010/11/stream-an-inotifypropertychanged-propertys-values-through-an-iobservable/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 18:13:47 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[System.Reactive]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[IObservable]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=190</guid>
		<description><![CDATA[One of the new .NET technologies that is really exciting to me these days is the Reactive Extensions to .NET (RX). Sometimes it&#8217;s called LINQ to Events, because you can write LINQ queries against future values (events, nicely wrapped up into the IObservable&#60;T&#62; interface), instead of against existing collections (IEnumerable&#60;T&#62;). This technology is especially useful [...]]]></description>
			<content:encoded><![CDATA[<p>One of the new .NET technologies that is really exciting to me these days is the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions to .NET (RX)</a>. Sometimes it&#8217;s called LINQ to Events, because you can write LINQ queries against <em>future </em>values (events, nicely wrapped up into the IObservable&lt;T&gt; interface), instead of against existing collections (IEnumerable&lt;T&gt;). This technology is especially useful in stateful programming models, such as when you&#8217;re building ViewModels for WPF or Silverlight. Once you start programming with RX (although it&#8217;s got a steep learning curve!), you start to see lots of places where it would really help make your code simpler. I saw one such place: whenever you need to programatically respond to an INotifyPropertyChanged notification.</p>
<h1>INotifyPropertyChanged</h1>
<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged </a>is an interface that most viewmodels need to implement. It&#8217;s used implicitly by the Silverlight and WPF data binding system to register a databinding&#8217;s interest in the fact that a property has changed, thus keeping all bindings to the same property up to date. When you implement it, you&#8217;re responsible for firing a PropertyChangedEvent event every time a property changes, with the name of the property as a parameter to the event. </p>
<p>Sometimes, you might want to programatically watch changes to a property too. Imagine a screen where users can add rows of data that represent orders. If there needs to be a &#8220;grand total&#8221; on the screen, then one viewmodel (possibly the root VM for the whole screen) will want to subscribe to the PropertyChanged event of each of the order&#8217;s Viewmodels. However, there&#8217;s a nicer programming model for listening to updates (events etc) than the INotifyPropertyChanged event&#8230;</p>
<h1>IObservable</h1>
<p><a href="http://msdn.microsoft.com/en-us/library/dd990377.aspx">IObservable </a>is the core of all RX programming (like IEnumerable is to LINQ). If you want to expose a source of data, you need to expose an IObservable. There&#8217;s already a <a href="http://msdn.microsoft.com/en-us/library/ff707291(v=VS.92).aspx">utility method</a> to turn an event into an IObservable. But this Observable will publish IEvents, which isn&#8217;t quite what I was after. What I wanted was to create an IObservable of the new <em>values </em>of the viewmodel&#8217;s property. Just like LINQ, we can use the &#8220;Select&#8221; method to acheive this.</p>
<h1>Funcy Expressions</h1>
<p>An Expression is a C#3 construct that allows you to pass expression trees around. This is a very popular way for you to strongly type property names, because you can reflect over an Expression<Func<ViewModel, PropertyType>> to get the name of the Property. You can also Compile() the expression to be able to execute it. My method uses both of these: It needs to know which PropertyChangedEvents it should react to (the Where() clause), and it needs to read the new value out (the Select() clause).</p>
<p><script src="http://gist.github.com/620226.js?file=Extensions.cs"></script></p>
<h1>The tests</h1>
<p>Here are the unit tests for this extension method. I had to create a dummy view model class to test, named &#8220;PropertyChanger&#8221;. Note how you can supply &#8220;true&#8221; to the startWithCurrent parameter to make sure your subscription will instantly start with the current value of the property, as well as receiving new values whenever a PropertyChangedEvent is fired.<br />
<script src="http://gist.github.com/620226.js?file=ExtensionsTests.cs"></script></p>
<p>Enjoy!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=0VkD4q-tB50:a5GY-sluJQs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=0VkD4q-tB50:a5GY-sluJQs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=0VkD4q-tB50:a5GY-sluJQs:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2010/11/stream-an-inotifypropertychanged-propertys-values-through-an-iobservable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The new StoryQ</title>
		<link>http://www.robfe.com/2010/06/the-new-storyq/</link>
		<comments>http://www.robfe.com/2010/06/the-new-storyq/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 10:21:52 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Me]]></category>
		<category><![CDATA[StoryQ]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=186</guid>
		<description><![CDATA[I was recently interviewed for a podcast about my Behaviour Driven Development framework, StoryQ. David Starr from Pluralsight did a great job with the interview &#8211; check it out at www.pluralsight-training.net/community/blogs/pluralcast/archive/2010/06/21/pluralcast-18-bdd-in-net-with-storyq.aspx. David also gave a great presentation on BDD at the 2010 tech ed in New Orleans, and I highly recommend it for anyone wondering [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://storyq.codeplex.com/"><img title="StoryQ" src="http://download.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=storyq&amp;DownloadId=103231&amp;Build=16821" alt="" width="234" height="87" /></a></p>
<p>I was recently interviewed for a podcast about my Behaviour Driven Development framework, <a href="http://storyq.codeplex.com">StoryQ</a>. <a href="http://www.pluralsight-training.net/community/blogs/starr/default.aspx">David Starr</a> from Pluralsight did a great job with the interview &#8211; check it out at <a href="http://www.pluralsight-training.net/community/blogs/pluralcast/archive/2010/06/21/pluralcast-18-bdd-in-net-with-storyq.aspx">www.pluralsight-training.net/community/blogs/pluralcast/archive/2010/06/21/pluralcast-18-bdd-in-net-with-storyq.aspx</a>.</p>
<p>David also gave a great presentation on BDD at the 2010 tech ed in New Orleans, and I highly recommend it for anyone wondering how to get started, or even whether they should get started, with BDD: <a href="http://www.msteched.com/2010/NorthAmerica/DPR302">http://www.msteched.com/2010/NorthAmerica/DPR302</a></p>
<h2>Improvements</h2>
<p>I think this is a good opportunity to talk about some of the new features in StoryQ. My <a href="http://www.robfe.com/2008/07/storyq-bdd-acceptance-testing-with-a-little-help-from-linq/">first post on StoryQ</a> came when we&#8217;d just committed it to codeplex, and a lot has changed since then:</p>
<ul>
<li>We&#8217;ve moved to Mercurial, which means our users can create <a href="http://storyq.codeplex.com/SourceControl/network">public forks</a></li>
<li><a href="http://storyq.codeplex.com/Thread/View.aspx?ThreadId=71553">No more ()=&gt; operator</a>. Thanks to <a href="http://flit.codeplex.com/">FLIT</a>, our fluent interface has evolved to accept plain old delegates, instead of Expression&lt;Action&gt;s. </li>
<li><a href="http://storyq.codeplex.com/wikipage?title=Tagging">Tagging</a>. Any Step can be &#8220;tagged&#8221;, which makes it easy to find in the output report</li>
<li>By default, the HTML report generated by StoryQ is JQuery-enriched, which makes it easy to narrow down stories by class hierarchy or tag. I&#8217;m particularly proud of this report &#8211; it&#8217;s a great way to share test results with everybody, especially when published from a continuous integration server.</li>
<li>A rewritten <a href="http://storyq.codeplex.com/wikipage?title=GUI">converter gui</a>, which lets you convert plain text stories into StoryQ code. The new version lets you choose what level of code generation you want (from Story initialisation statement to entire test class), and offers a basic form of intellisense.</li>
</ul>
<h2>Roadmap</h2>
<ul>
<li>The new fluent interface architecture allows us to support multiple (human) languages, and I&#8217;m looking forward to creating fluent interfaces for non-english speakers.</li>
<li>I think we&#8217;ll be able to create a new way of doing BDD in .NET that takes advantage of C# 4.0&#8242;s dynamic features</li>
<li>We still haven&#8217;t added xUnit support! Which is lame, because it&#8217;s probably going to be really easy&#8230; </li>
</ul>
<p>Please check StoryQ out and let us know if you&#8217;ve got any bright ideas for it! And if you&#8217;ve never tried BDD, you should definitely look into it. It&#8217;s even more fun than TDD!!!</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">
<p><a href="http://www.robfe.com/2008/07/storyq-bdd-acceptance-testing-with-a-little-help-from-linq/">http://www.robfe.com/2008/07/storyq-</a></p>
<p><a href="http://www.robfe.com/2008/07/storyq-bdd-acceptance-testing-with-a-little-help-from-linq/">bdd-acceptance-testing-with-a-little-help-from-linq/</a></p>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=5i8SL8h8IFg:cCYGQDKBpdM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=5i8SL8h8IFg:cCYGQDKBpdM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=5i8SL8h8IFg:cCYGQDKBpdM:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2010/06/the-new-storyq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Curious Case of the DesignData msbuild target</title>
		<link>http://www.robfe.com/2009/12/the-curious-case-of-the-designdata-msbuild-target/</link>
		<comments>http://www.robfe.com/2009/12/the-curious-case-of-the-designdata-msbuild-target/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 18:46:19 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Blendability]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Blend3]]></category>
		<category><![CDATA[DesignData]]></category>
		<category><![CDATA[developer designer workflow]]></category>
		<category><![CDATA[Visualisation]]></category>

		<guid isPermaLink="false">http://www.robfe.com/?p=178</guid>
		<description><![CDATA[Thanks to Karl Shifflet and Unni Ravindranathan, I&#8217;ve finally gotten my head around a superior method of populating Blend (and VS 2010&#8242;s WPF designer) with sample data. This method, which I am going to call the &#8220;DesignData build target&#8221;, has the following advantages: Blend will render your control as though it&#8217;s running with real data, [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to <a href="http://karlshifflett.wordpress.com/2009/10/21/visual-studio-2010-beta2-sample-data-project-templates/">Karl Shifflet</a> and <a href="http://blogs.msdn.com/unnir/archive/2009/07/12/introducing-sample-data-for-developers.aspx">Unni Ravindranathan</a>, I&#8217;ve finally gotten my head around a superior method of populating Blend (and VS 2010&#8242;s WPF designer) with sample data. This method, which I am going to call the &#8220;DesignData build target&#8221;, has the following advantages:</p>
<ul>
<li>Blend will render your control as though it&#8217;s running with real data, as you design.</li>
<li>You won&#8217;t have to look up and type magic strings when you&#8217;re creating your bindings in Blend, Blend will be able to list the possible properties for you. Intellisensational!</li>
<li>Once compiled, your output dll will have NO baggage associated with your designery frivolities.</li>
<li>You don&#8217;t have to write lots of dummy / mock / stub code</li>
<li>You don&#8217;t even have to finish writing your viewmodel: however you DO have to write all your properties. This is a Good Thing, because it means your bindings will have the right magic strings in them.</li>
</ul>
<h2>How does it work?</h2>
<p>First, you need a xaml file that builds up a sample instance of your viewmodel. Then all you have to do is set your Blend-specific DataContext to read from that file.</p>
<h3>How do I tell Blend where to get this design data?</h3>
<p>I&#8217;ve <a href="http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/">already blogged</a> about the d:DataContext attribute, letting you set up a DataContext but only inside Blend. Another secret of the &#8220;d&#8221; xml namespace* is the {d:DesignData Source=<em>someDesignDataFile.xaml</em>} <a href="http://msdn.microsoft.com/en-us/library/ms747254.aspx">markup extension</a>. So all you need in your UserControl or Window&#8217;s xaml is (usually on the first element):</p>
<p><span style="font-family: 'Courier New';">d:DataContext=&#8221;{d:DesignData Source=<em>someDesignDataFile.xaml</em>}&#8221;</span></p>
<p><a href="http://karlshifflett.wordpress.com/2009/10/21/visual-studio-2010-beta2-sample-data-project-templates/">Karl&#8217;s blog post</a> explains this in a little more depth.</p>
<h3>What should be in this design data xaml file?</h3>
<p>Just like you usually declare and populate a Window or UserControl, you can actually declare and populate your own view-models as the root element of a xaml file.</p>
<p>I got myself quite confused when I started working with this, because i didn&#8217;t realise that the <strong>root element</strong> of the xaml file should be a declaration of your viewmodel (I was actually placing my viewmodel within a ResourceDictionary &gt;&lt; ):</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" src="http://www.robfe.com/wp-content/uploads/2009/12/image.png" border="0" alt="image" width="552" height="106" /></p>
<p>Here you can see I&#8217;ve defined a new ScrumBoardDesignDataDemo.ViewModel.Board, and started assigning some StageNames to it. I&#8217;ve used the clr namespace of my viewmodel classes (&#8220;ScrumBoardDesignDataDemo.ViewModel&#8221;) as the default xml namespace, instead of using what xaml files usually give you: the WPF control namespace. This just cuts down on the amount of typing required.</p>
<p>Normally, if you&#8217;re trying to instantiate a class without a public, parameterless constructor in xaml, you&#8217;ll get a compiler error. You also won&#8217;t be able to set properties that don&#8217;t have public setters. This technique allows Blend to do a bit of magic (reflectively creating a doppelganger of your class) that means you can bend the rules a little. More on that in my next post. Let&#8217;s just concentrate on getting some sample data into Blend.</p>
<p>By now, if you go into Blend and you try to set up a binding through the binding dialog (you get this by clicking on the peg next to a property, say ItemsSource, and choosing Binding), you&#8217;ll get  this helpful dialog:</p>
<p><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" src="http://www.robfe.com/wp-content/uploads/2009/12/image1.png" border="0" alt="image" width="535" height="321" /></p>
<p>See how the &#8220;Fields&#8221; tree is populated? That&#8217;s Blend&#8217;s version of intellisense, which means you no longer have to rely on knowing what the right property name is and hand-typing it.</p>
<p>Don&#8217;t go away! We are only half finished. Blend might be helping you choose property names, but we&#8217;re left with two more problems:</p>
<ul>
<li>Blend isn&#8217;t displaying the sample data on screen.</li>
<li>This xaml file full of things that were only useful during development is being shipped to our customers inside our DLL.</li>
</ul>
<p>We can fix this with a simple, but quirky little feature. By setting our design data file&#8217;s build action to &#8220;DesignData&#8221; we will have both of our problems fixed. Blend will realise that it&#8217;s ok to try and instantiate the object in the xaml file, and MSBuild will leave that xaml file out of our dll.</p>
<h2>Setting DesignData build action for the first time</h2>
<p>Normally, if you have a look at the properties of a xaml file in visual studio you&#8217;ll see that the Build Action is set to &#8220;Page&#8221;, or in the case of App.xaml it&#8217;s &#8220;ApplicationDefinition&#8221;. You&#8217;d think that it&#8217;s just a simple matter of typing the word &#8220;DesignData&#8221; into that combobox, but if you try this, you&#8217;ll get an exception message. Karl&#8217;s blog post is about a template he wrote that gets over this problem (by creating the file with all the right properties for you), but I had to figure out how the magic worked. It turns out that it&#8217;s relatively easy to work around this, you just have to edit the csproj file manually. I&#8217;ll walk you through doing this with visual studio – although you could just as easily use notepad.</p>
<p>Save all your files, right click your WPF project and choose &#8220;Unload&#8221;. This puts your project into a disabled state where you can&#8217;t do anything but hand edit the xml – which is exactly what we want to do.</p>
<ol>
<li>Right click the (now greyed out) project file and choose &#8220;Edit&#8221;.</li>
<li>Locate the design data xaml file: <img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" src="http://www.robfe.com/wp-content/uploads/2009/12/image2.png" border="0" alt="image" width="352" height="74" /></li>
<li>Edit the element to be a &#8220;DesignData&#8221; element with no children: <img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" src="http://www.robfe.com/wp-content/uploads/2009/12/image3.png" border="0" alt="image" width="319" height="26" /></li>
<li>Save your csproj file, right click it and choose &#8220;Reload&#8221;</li>
</ol>
<p>Now if you compile your project, you&#8217;ll find that all traces of this design data have been erased. Even better, if you go back to blend, you&#8217;ll see that your sample data is now present (you may have to rebuild or even reload the project):</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://www.robfe.com/wp-content/uploads/2009/12/image4.png" border="0" alt="image" width="568" height="311" /></p>
<p>So hopefully you&#8217;ve got another tool in your toolbox to help you (or your graphic designer) be effective in Blend. This is my favourite method so far, however there&#8217;s a couple of situations where it might be unsuitable. My <em>next</em> post will be all about why, but just so you know, this doesn&#8217;t work well when:</p>
<ul>
<li>You want custom logic to occur in your viewmodel at design time (ie a Color property on your viewmodel changes whenever another integer property goes below zero)</li>
<li>You are using DataTemplates with no Key, just a DataType, and are relying on WPF to find the Template by your ViewModel class. (I understand that Silverlight doesn&#8217;t support this anyway, so no problem there!)</li>
</ul>
<p>As always, I&#8217;m keen to know if I got anything wrong. There isn&#8217;t much information about the whole &#8220;d:&#8221; namespace on the internet! Also, my third and final post in this series (about the magic that makes this work and how said magic causes the above problems) will come with a demo project.</p>
<p>* This namespace is actually <em>http://schemas.microsoft.com/expression/blend/2008, </em>but Blend always imports this as &#8220;d&#8221;</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/RFE?a=lKh_3k_dTqg:5rlvcOWTcl4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/RFE?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/RFE?a=lKh_3k_dTqg:5rlvcOWTcl4:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/RFE?i=lKh_3k_dTqg:5rlvcOWTcl4:D7DqB2pKExk" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://www.robfe.com/2009/12/the-curious-case-of-the-designdata-msbuild-target/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
