<?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>Jeff Wilcox &#187; Software Development</title>
	<atom:link href="http://www.jeff.wilcox.name/topics/dev/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jeff.wilcox.name</link>
	<description>Silverlight, rich client apps and web development</description>
	<lastBuildDate>Mon, 26 Jul 2010 17:56:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Frame rate counters in Windows Phone</title>
		<link>http://www.jeff.wilcox.name/2010/07/counters/</link>
		<comments>http://www.jeff.wilcox.name/2010/07/counters/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 16:29:25 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/07/counters/</guid>
		<description><![CDATA[Information about the frame rate counters and graphics stats for analyzing Silverlight for Windows Phone applications.]]></description>
			<content:encoded><![CDATA[<p>While developing Windows Phone applications, it’s good to have some simple but important performance tips and tricks in your back pocket. Here’s a quick reference to enabling frame rate counters plus an overview of what the values represent.</p>
<h3>Enable frame rate counters in code</h3>
<p>In your App.xaml.cs or MainPage.xaml.cs, in the constructor, set the host property to true for this diagnostic mode:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:378ddd5a-123a-41a2-a6ef-0f9fd6d5a856" class="wlWriterEditableSmartContent">
<pre class="c-sharp" name="code">Application.Current.Host.Settings.EnableFrameRateCounter = true;</pre>
</div>
<h3>Make sure the System Tray is not visible</h3>
<p>By default in the beta tools, the MainPage.xaml sets the system tray to be visible. When this happens, the frame rate counters are hidden by the operating system shell.</p>
<h4>Method 1: XAML</h4>
<p>The default page template includes an XMLNS declaration for “shell”, and has this in the phone application page constructor:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:dd7b0f4f-0bde-4d4b-ad6f-c8ab434439e4" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">shell:SystemTray.IsVisible="true"</pre>
</div>
<p>Just change the IsVisible property to False:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:a0e29e6c-c60c-4e75-b7cf-4ed385579858" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">shell:SystemTray.IsVisible="false"</pre>
</div>
<h4>Method 2: Code</h4>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:7dabaf74-49ed-4989-8fbb-fa60197a381f" class="wlWriterEditableSmartContent">
<pre class="c-sharp" name="code">Microsoft.Phone.Shell.SystemTray.IsVisible = false;</pre>
</div>
<p>In a future release of the phone tools, this is actually going to be less of an issue, as the counters will actually be right-aligned on the screen instead.</p>
<h3>Adding a simple check box to toggle the counters</h3>
<p>A lot of app developers add a check box to debug builds that lets them toggle this sort of diagnostic display. In one of our ‘Scenarios’ test applications, we have a check box on the first page, and in XAML it connects the Checked and Unchecked events to this method.:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:4c41d953-1c3e-46ff-a26a-b90e550b4487" class="wlWriterEditableSmartContent">
<pre class="c-sharp" name="code">private void FrameRateCounters_Checked(object sender, RoutedEventArgs e)
{
    var checkbox = (CheckBox)sender;
    var newValue = checkbox.IsChecked.GetValueOrDefault();

    Application.Current.Host.Settings.EnableFrameRateCounter = newValue;
    SystemTray.IsVisible = !newValue; // Hides frame rate counter otherwise
}</pre>
</div>
<h3>Enabling frame rate counters only on debug builds</h3>
<p>You can also use conditional compilation to just have your debug builds display this information. Add this to your App.xaml.cs:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:0e8e0218-898c-4457-b710-69a38d76f8b5" class="wlWriterEditableSmartContent">
<pre class="c-sharp" name="code">#if DEBUG
    Application.Current.Host.Settings.EnableFrameRateCounter = true;
    Microsoft.Phone.Shell.SystemTray.IsVisible = false;
#endif</pre>
</div>
<p>This assumes you remember to eventually ship your app on the marketplace with a release build <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/07/wlEmoticonsmile.png" />.</p>
<h3>Accelerated graphics note: If you still don’t see a frame rate counter</h3>
<p>The frame rate counter only appears when your system has a supported DirectX 10 graphics card that allows the Windows Phone emulator to use accelerated graphics.</p>
<p>If you set the frame rate counter visibility to True, the system tray is hidden, and you still don’t’ see the counters, then unfortunately your system does not have a supported card for displaying this information.</p>
<p>All Windows Phone devices will show the frame rate counter, so once phone hardware is more widely available, you’ll still have an option to test the performance of your apps.</p>
<h3>Exploring the frame rate counter data</h3>
<p>This has been covered countless times, but I figure if you’re [using your search engine of choice to find this] here that it doesn’t hurt to duplicate.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" class="wlDisabledImage" title="BetaCounters" border="0" alt="BetaCounters" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/07/BetaCounters.png" width="685" height="265" /></p>
<p><em>The Beta tools display frame counter information on the top of the page.</em></p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" class="wlDisabledImage" title="NewerCounters" border="0" alt="NewerCounters" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/07/NewerCounters.jpg" width="486" height="422" /></p>
<p><em>Shipping frame counter information is displayed on the right of the screen.</em></p>
<p>So moving through the counters, we have the following.</p>
<p><strong>Render Thread FPS:</strong> The number of frames per second that the independent simple animations and rendering thread is using. Keeping around 60 will provide a great experience, while a number of 30 fps will begin to show a poor experience to the end user.</p>
<p>Under 30 fps this counter will turn red in post-beta builds.</p>
<p><strong>User Interface Thread FPS:</strong> The number of fps that the primary user interface thread is experiencing. Property change notifications, data binding, primary managed code execution, and animations not handled on the render thread use this threads’ resources.</p>
<p>Turns red when the count is at or below 15 fps.</p>
<p><strong>Texture Memory Usage: </strong>A specialized memory counter indicating the video memory used for storing application textures.</p>
<p><strong>Surface Counter: </strong>A count of the number of surfaces that are passed to the graphics chip.</p>
<p><strong>Intermediate Texture Count:</strong> The number of intermediate textures created for compositing.</p>
<p><strong>Screen Fill Rate:</strong> A metric representing the number of complete phone screens being painted each and every frame.</p>
<p>This counter was not present in the Beta tools and is a new metric for post-Beta use.</p>
<h3>Target frame rates for good performance</h3>
<p>When testing on a Windows Phone device, here are key performance metrics to try for. Understand that the emulator (XDE) performance may not be indicative of actual device performance.</p>
<p>Frame rate counters may be 0 when there is no animation being updated on the thread at any particular moment. You can add a very simple, continually animating and repeating, animation to your application during development &amp; testing if you want to ensure that there is always some frame rate value available.</p>
<table border="0" cellspacing="0" cellpadding="4" width="641">
<tbody>
<tr>
<td valign="top" width="171"><em>Counter</em></td>
<td valign="top" width="162"><em>Ideal Minimum</em></td>
<td valign="top" width="155"><em>Best Experience</em></td>
<td valign="top" width="151"><em>Theoretical Max</em></td>
</tr>
<tr>
<td valign="top" width="182">Render Thread</td>
<td valign="top" width="170">30 fps</td>
<td valign="top" width="162">60 fps</td>
<td valign="top" width="156">120 fps</td>
</tr>
<tr>
<td valign="top" width="184">UI Thread</td>
<td valign="top" width="173">15 fps</td>
<td valign="top" width="165">&gt; 15 fps</td>
<td valign="top" width="159">120 fps</td>
</tr>
<tr>
<td valign="top" width="183">Screen Fill Rate</td>
<td valign="top" width="173">1.0</td>
<td valign="top" width="167">&lt;= 2.0</td>
<td valign="top" width="161"><font color="#a5a5a5">N/A</font></td>
</tr>
</tbody>
</table>
<p>Future posts will cover tips for improving the frame rate and application performance. Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/07/counters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Updated Silverlight Unit Test Framework bits for Windows Phone and Silverlight 3</title>
		<link>http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/#comments</comments>
		<pubDate>Thu, 27 May 2010 21:02:52 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight Toolkit]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/</guid>
		<description><![CDATA[Here's the same unit test framework from the April 2010 Silverlight Toolkit, built for Windows Phone and SL3 developers only.]]></description>
			<content:encoded><![CDATA[<p>Here are updated quasi-official unit test framework bits for Silverlight 3 and Windows Phone developers. These are <strong>not</strong> intended for Silverlight 4 developers, since the same framework built for SL4 is included in the <a href="http://silverlight.codeplex.com/">April 2010 Silverlight Toolkit</a>.</p>
<p>This brings the <a href="http://www.jeff.wilcox.name/2010/05/new-2010-test-framework/">new features</a> from the Silverlight 4 version to developers who have a business reason to continue with Silverlight 3 development for the time being:</p>
<ul>
<li>Updated user interface</li>
<li>Integrated “tag expression” support for selecting subsets of tests to run</li>
<li>Performance improvements</li>
<li>Removal of dependencies on XLinq and System.Windows.Browser assemblies</li>
</ul>
<p>These are also the bits you want for Windows Phone testing.</p>
<h4>Why wasn’t there one for Silverlight 3 already?</h4>
<p>Since the April 2010 toolkit release was targeted for Silverlight 4 developers only, these bits were not released for version 3 (though were built from the same source).</p>
<h4>Why doesn’t the April 2010 toolkit work for Windows Phone development &amp; testing?</h4>
<p>The Windows Phone development environment is based on a version of Silverlight 3 today, and so that means that you need to use Silverlight 3 binaries and class libraries when re-using Silverlight apps and code – <em>not</em> Silverlight 4.</p>
<p>These bits work well for phone developers and replace the older bits I had posted to my <a href="http://www.jeffatmix.com/">MIX talk site</a>.</p>
<h4>Download the binaries</h4>
<p>[<a href="http://media.jeff.wilcox.name/blog/ut/SL3_UTF_May.zip"><strong>Silverlight 3 binaries for the Silverlight Unit Test Framework</strong></a>, Zip 452KB]    <br />You may need to ‘unlock’ the binaries for security reasons once downloading and extracting the assemblies from the .Zip. To do this, right-click on the file and select the ‘Unlock’ button.</p>
<p>These binaries are strong named as before, but are <em>not</em> Authenticode signed, so they are not official. This helps work around some Windows Phone signing issues I’ve heard reports of.</p>
<p>Hope this helps,   <br />Jeff</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>How about a Zune-style ChildWindow?</title>
		<link>http://www.jeff.wilcox.name/2010/05/my-childwindow-design/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/my-childwindow-design/#comments</comments>
		<pubDate>Fri, 21 May 2010 21:25:39 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight Toolkit]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/my-childwindow-design/</guid>
		<description><![CDATA[Today I am sharing my ChildWindow style that resembles the Zune software user interface and has a nice transition. Enjoy!]]></description>
			<content:encoded><![CDATA[<p>Today I’m sharing my new ChildWindow style. It is a differentiated child window designed in that it doesn’t have a close button, has a completely different animation in and out, and I thought I was worth sharing. I’ve included a runtime app so you can run it and <a href="http://media.jeff.wilcox.name/blog/cw/index.html">see for yourself</a>.</p>
<h3>My ChildWindow style</h3>
<p><a href="http://media.jeff.wilcox.name/blog/cw/index.html"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="mycw" border="0" alt="mycw" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/mycw.png" width="680" height="359" /></a>     <br /><em>Click on the window above to open a simple Silverlight 4 application that demonstrates the transitions and interactivity. <a href="http://media.jeff.wilcox.name/blog/cw/ChildWindowTheme.zip">Project download</a>.</em></p>
<p>Some things to call out:</p>
<ul>
<li>I don’t include a Close button in the window chrome.</li>
<li>I hook up to the OnKeyDown event in my sample implementation. I always try and do this with my ChildWindows so that the escape (ESC) key can be treated as a cancelation of the dialog. Personal preference but a usability win I believe.</li>
<li>I like a light overlay color instead of a darkening experience, and went for that look.</li>
<li>My actual implementation uses a value converter to capitalize the title. I’ve removed this from my template for the time being.</li>
</ul>
<h3>The story on my evolving, unnamed theme, and how it relates to “Cosmopolitan”</h3>
<p>There’s an excellent <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/9329bdf4-3be7-4347-b1cd-b2c5d4e5a293">“Cosmopolitan” Silverlight project template</a> + theme available that makes building good-looking interfaces a snap, and I’d highly recommend it if you’re looking to modernize the look of a new Silverlight project. I believe it pulls from “codename Metro” design ideas. It just works and as a VS template it rocks!</p>
<p>I’ve built an alternative, but similar theme, over time that I use on many of my projects, and it also pulls from the inspiration of the clean, consistent <a href="http://www.zune.net/en-US/products/software/default.htm">Zune software</a> design principals.</p>
<p>Now that the “Cosmopolitan” theme is out there, I’ve been taking the time to compare and contrast my similar theme with this, and see where I can make changes. Yeah, the things I do in my free time are baffling…</p>
<p>This is a good exercise because design is a two-way street, comparing and contrasting design decisions and implementations: I’ve learned that I should have been including validation templates in my theme (oops, haven’t used that feature enough). And I’ve shared some minor feedback on parts of the “Cosmopolitan” theme’s implementation details with its designers.</p>
<p>In the future I’ll present the complete theme for many controls, but until that develops, I’m going to continue to share small styles and templates, along with my comments along the way. Previously I blogged my <a href="http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/">context menu style</a>.</p>
<p>If you’re wondering “why should I use ChildWindow?” &#8211; I used to wonder the same thing. But I’m using <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.childwindow(VS.95).aspx">ChildWindow</a> more now than ever. I’ve discovered the importance of the nice integration with Visual Studio (there’s an item template for child windows), and out-of-browser applications have many uses for a rich modal-style window for sharing information at runtime.</p>
<p>I’ve completely replaced the MessageBox in my out-of-browser applications to instead use a child window designed to replace the message box functionality, offering a consistent visual design even when a message box-like experience is needed. I even use extension methods to add methods to MessageBox to instead use my styled child window.</p>
<h3>Other ChildWindow styles</h3>
<p>Here’s the standard ChildWindow style and control template that is built into the Silverlight SDK. I’m displaying a password entry form adapted from an app I was experimenting with:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="cw1" border="0" alt="cw1" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/cw1.png" width="685" height="239" /> </p>
<p>Here is the same window with the “Cosmopolitan” theme’s style applied:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="cwcosmo" border="0" alt="cwcosmo" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/cwcosmo.png" width="685" height="274" /> </p>
<h3>Note: There’s a bug in ChildWindow implicit styling support</h3>
<p>While working on creating themes, I did discover that there’s an unfortunate bug in Silverlight 4 where the implicit styles for ChildWindow are not picked up in certain XAML scenarios. Namely, if you use the handy item template in Visual Studio, the implicit style won’t be picked up.</p>
<p>Oddly, at times Visual Studio will show the proper implicit style, but at runtime it will revert to the standard control default style. Here’s a small screenshot – this is out-of-the-box “Cosmopolitan” theme with a ChildWindow item template.</p>
<h4>At design time it looks fine:</h4>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="dt" border="0" alt="dt" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/dt.png" width="685" height="454" /> </p>
<h4>At runtime:</h4>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="runtime_style_not_applied_bug" border="0" alt="runtime_style_not_applied_bug" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/runtime_style_not_applied_bug.png" width="685" height="231" /> </p>
<p>It appears that this item template format, where the XAML file of the child window’s root is the child window, doesn’t allow the style that was implicitly defined to be picked up.</p>
<p>No worries. To workaround this, add a Style attribute to the root of the file and a static resource to ChildWindow name. If you’re working with “Cosmopolitan”, then here are the steps:</p>
<ul>
<li>Open the Assets/SDKStyles.xaml file</li>
<li>Navigate to the implicit style for ChildWindow around line 2,440</li>
<li>Add an x:Key to make the style explicit instead of implicit. x:Key=”ChildWindowStyle”</li>
<li>Add this line after the (now explicit) style:</li>
</ul>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:839e9ba9-7b8c-4d91-9a85-d509a86d8e22" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Style TargetType="controls:ChildWindow" BasedOn="{StaticResource ChildWindowStyle}" /&gt;</pre>
</div>
<ul>
<li>Open your ChildWindow XAML file (mine is called Password.xaml) and add the attribute Style=”{StaticResource ChildWindowStyle}” to the root element</li>
</ul>
<h4>And here’s it at runtime now with our fix/workaround:</h4>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="cwcosmo" border="0" alt="cwcosmo" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/cwcosmo.png" width="685" height="274" /></p>
<p>Note that whenever defining implicit styles myself, I always start explicit, then provide the implicit in the file using BasedOn.</p>
<h4>Download my sample project including the style</h4>
<p>[<a href="http://media.jeff.wilcox.name/blog/cw/ChildWindowTheme.zip">ChildWindowTheme.zip</a>, 71 KB] Includes the theme in App.xaml.</p>
<h3>“My yet-to-be-named Zune-inspired theme” components</h3>
<ul>
<li>ChildWindow (this post)</li>
<li><a href="http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/">ContextMenu</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/my-childwindow-design/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Windows Phone? Sounds exciting!</title>
		<link>http://www.jeff.wilcox.name/2010/05/phone-developers-phone-developers/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/phone-developers-phone-developers/#comments</comments>
		<pubDate>Fri, 21 May 2010 19:35:22 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/phone-developers-phone-developers/</guid>
		<description><![CDATA[Just letting folks know... I'm working in a much more official capacity on the Silverlight and Windows Phone developer story.]]></description>
			<content:encoded><![CDATA[<p>As an FYI, I wanted to let people know that I’m now focusing much more exclusively on the Windows Phone project here at Microsoft. Though the organization boundaries aren’t that exciting, I am still part of the great Silverlight team – only now more focused on the phone development story.</p>
<p><object width="640" height="385"><param name="movie" value="http://www.youtube-nocookie.com/v/RWtlxXC0Xnc&amp;hl=en_US&amp;fs=1&amp;rel=0&amp;color1=0x2b405b&amp;color2=0x6b8ab6"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/RWtlxXC0Xnc&amp;hl=en_US&amp;fs=1&amp;rel=0&amp;color1=0x2b405b&amp;color2=0x6b8ab6" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object></p>
<p>It’s a familiar crowd: many of the brightest from across the company have been joining the ranks, and a lot of the classic Silverlight Toolkit team members are a part of the effort.</p>
<p>The focus of this blog won’t be changing much at all – I continue to be involved in Silverlight Toolkit, the Silverlight Unit Test Framework, and anything else I can get my hands on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/phone-developers-phone-developers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Silverlight 4 features to create a Zune-like context menu</title>
		<link>http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/#comments</comments>
		<pubDate>Sat, 15 May 2010 19:25:12 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight Toolkit]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/</guid>
		<description><![CDATA[A customized Silverlight 4 ContextMenu control that resembles the crisp, simple look of the Zune software's context menu.]]></description>
			<content:encoded><![CDATA[<p>Trying to create a modern, clean and crisp user interface is a challenge – and it’s something that Zune has done rather well in both their software and hardware experiences.</p>
<p>I took a few minutes to experiment with new Silverlight 4 features, including the new <a href="http://silverlight.codeplex.com/">Silverlight Toolkit</a> (April 2010 release) that includes a context menu control, to re-style/re-template the menu to look similar to a few other menus.</p>
<p>Here’s a quick look at some common context menu visuals – clearly there is some room for artistry in creating a consistent experience with your app.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ContextMenus" border="0" alt="ContextMenus" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/ContextMenus.png" width="680" height="330" /> </p>
<p>The center context menu, with the Windows look, is what the default Silverlight Toolkit context menu looks most similar to.</p>
<h3>New features used</h3>
<ul>
<li>Right-click input event, added to the platform in Silverlight 4</li>
<li>Context menu control from the Silverlight Toolkit</li>
<li>Implicit styles support</li>
<li>Local fonts</li>
</ul>
<h3>Consider checking out ‘Cosmopolitan’, too</h3>
<p>There’s a theme that resembles the modern “codename Metro” design style, similar to that of the Zune user interface, that is available for Silverlight 4. <a href="http://timheuer.com/blog/archive/2010/05/03/new-silverlight-4-themes-available-for-download.aspx">More information is available on Tim’s blog</a>.</p>
<h3>What a context menu looks like in XAML</h3>
<p>You need an xmlns for the input assembly in the Silverlight Toolkit. Then you setup the ContextMenuService, a ContextMenu instance, plus multiple MenuItem and Separator instances.</p>
<p>A MenuItem can optionally have an icon, though I believe the trend these days is moving away from the icon-heavy menu and toolbar world into a clean &amp; crisp text-only experience… so I prefer a styled context menu that doesn’t optimize for icons.</p>
<p>The XMLNS for the context menu assembly is:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:9c30beb8-bc99-4dd4-9b26-528b0155f629" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">xmlns:controlsInputToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"</pre>
</div>
<p>You can directly wire up to the Click event, or use Commands. Here’s a sample context menu within a data template:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:f1699113-aaec-4a27-8290-b5a8687024a8" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;ListBox.ItemTemplate&gt;
    &lt;DataTemplate&gt;
        &lt;ContentPresenter Content="{Binding}"&gt;
            &lt;controlsInputToolkit:ContextMenuService.ContextMenu&gt;
                &lt;controlsInputToolkit:ContextMenu&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Play" Click="OnMenuItemClick"/&gt;

                    &lt;controlsInputToolkit:Separator/&gt;

                    &lt;controlsInputToolkit:MenuItem Header="Download" Click="OnMenuItemClick"/&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Buy" Click="OnMenuItemClick"/&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Add to cart" Click="OnMenuItemClick"/&gt;

                    &lt;controlsInputToolkit:Separator/&gt;

                    &lt;controlsInputToolkit:MenuItem Header="Add to playlist" Click="OnMenuItemClick"/&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Add to burn list" Click="OnMenuItemClick"/&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Add to now playing" Click="OnMenuItemClick"/&gt;
                    &lt;controlsInputToolkit:MenuItem Header="Mark as favorite" Click="OnMenuItemClick"/&gt;

                    &lt;controlsInputToolkit:Separator/&gt;

                    &lt;controlsInputToolkit:MenuItem Header="Send" Click="OnMenuItemClick"/&gt;

                &lt;/controlsInputToolkit:ContextMenu&gt;
            &lt;/controlsInputToolkit:ContextMenuService.ContextMenu&gt;
        &lt;/ContentPresenter&gt;
    &lt;/DataTemplate&gt;
&lt;/ListBox.ItemTemplate&gt;</pre>
</div>
<p>And here’s what it looks like:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="DefaultContextMenu" border="0" alt="DefaultContextMenu" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/DefaultContextMenu.png" width="188" height="242" /> </p>
<p>To use the ContextMenu, make sure your project includes references to <em>both</em> the toolkit’s System.Windows.Controls.Input.Toolkit.dll as well as the SDK’s System.Windows.Controls.dll.</p>
<p>Now I’d like to make this look more Zune-like.</p>
<h3>Using implicit styles</h3>
<p>So there are multiple ways to have a style (predefined look, settings and template) on your object:</p>
<ol>
<li>Default style key – the default template and style that the creator of the control had in mind. No work required.</li>
<li>Implicit styles defined in Resources – in Silverlight 4, a Style defined by a user, but without an x:Key property, will automatically apply to all scoped controls of that type.</li>
<li>Static resource styles defined in Resources – the standard experience up until now, having a Style with an x:Key, then setting the Style=”{StaticResource MyKeyName}” on any and all controls that want to use that style.</li>
<li>Setting properties directly on an object.</li>
</ol>
<p>So here is a standard, simple style for a Button, with the key:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:dc290aa0-a366-4943-89ce-8a6771e556a1" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;UserControl.Resources&gt;
    &lt;Style TargetType="Button" x:Key="MyButtonStyle"&gt;
        &lt;Setter Property="Background" Value="Blue"/&gt;
    &lt;/Style&gt;
&lt;/UserControl.Resources&gt;</pre>
</div>
<p>Here’s how you reference it:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:1c329b9f-9e83-41e4-9883-2927dfdb6c1e" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Button Style="{StaticResource MyButtonStyle}" Content="OK"/&gt;</pre>
</div>
<p>And now let’s make that into an implicit style for Silverlight 4. Just remove the x:Key:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:86e3e09e-40ad-4ef7-a8cb-6ad12d9df35a" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;UserControl.Resources&gt;
    &lt;Style TargetType="Button"&gt;
        &lt;Setter Property="Background" Value="Blue"/&gt;
    &lt;/Style&gt;
&lt;/UserControl.Resources&gt;</pre>
</div>
<p>And here’s how you reference that style – you don’t – it’s implicit:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:87648dd1-5f46-4050-af9d-07bf7335c0a9" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Button Content="OK"/&gt;</pre>
</div>
<p><em>Small caveat, fyi:</em> there is a bug with implicit styles not necessarily being applied within data templates. To work around this, I had to move to explicit styles (adding an x:Key to the style, then setting the Style property in the DataTemplate’s XAML to the static resource’s key).</p>
<h3>Local fonts</h3>
<p>I also used a feature of Silverlight 4 that lets me pick up and use local fonts on the machine. I’m using the ‘Segoe UI’ font, a key part of the Windows 7 user experience and visual identity.</p>
<p>However I also define fallback fonts, just like you would in HTML:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:a62b7fd6-6547-4165-9612-f4a9141b6a58" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Setter Property="FontFamily" Value="Segoe UI, Tahoma, Arial"/&gt;</pre>
</div>
<h3>My Zune-like context menu</h3>
<p>Here are the templates I ended up creating using Expression Blend.</p>
<p>To achieve the fade-in effect, I faked a little and used a Loaded event trigger, so the first time any particular context menu is shown, it will quickly fade – but subsequent presentations of the same instance will not fade, for a faster, more performant feel.</p>
<h4>ContextMenu Style</h4>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:d0a111a7-b70d-4f8b-b81a-abad98ad685e" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Style TargetType="controlsInputToolkit:ContextMenu" x:Key="ZuneLikeContextMenu"&gt;
    &lt;Setter Property="Background" Value="#FFFFFFFF"/&gt;
    &lt;Setter Property="BorderThickness" Value="0,1,0,1"/&gt;
    &lt;Setter Property="BorderBrush" Value="#0D000000"/&gt;
    &lt;Setter Property="Padding" Value="0,4,0,4"/&gt;
    &lt;Setter Property="Template"&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType="controlsInputToolkit:ContextMenu"&gt;
                &lt;Border
                    x:Name="Menu"
                    Opacity="0"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Background="{TemplateBinding Background}"
                    CornerRadius="0"&gt;
                    &lt;Border.Effect&gt;
                        &lt;DropShadowEffect
                            ShadowDepth="0" Opacity="0.6" BlurRadius="22"/&gt;
                    &lt;/Border.Effect&gt;
                    &lt;Border.Triggers&gt;
                        &lt;EventTrigger RoutedEvent="Rectangle.Loaded"&gt;
                            &lt;BeginStoryboard&gt;
                                &lt;Storyboard&gt;
                                    &lt;DoubleAnimation
                                        Duration="0:0:0.2"
                                        To="1"
                                        Storyboard.TargetProperty="Opacity"
                                        Storyboard.TargetName="Menu"/&gt;
                                &lt;/Storyboard&gt;
                            &lt;/BeginStoryboard&gt;
                        &lt;/EventTrigger&gt;
                    &lt;/Border.Triggers&gt;
                    &lt;Grid&gt;
                        &lt;ItemsPresenter Margin="{TemplateBinding Padding}"/&gt;
                    &lt;/Grid&gt;
                &lt;/Border&gt;
            &lt;/ControlTemplate&gt;
        &lt;/Setter.Value&gt;
    &lt;/Setter&gt;
&lt;/Style&gt;</pre>
</div>
<h4>Separator Style</h4>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:010d1470-b3e8-4932-8394-67b1a78e20ce" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Style TargetType="controlsInputToolkit:Separator" x:Key="ZuneLikeSeparator"&gt;
    &lt;Setter Property="Background" Value="LightGray"/&gt;
    &lt;Setter Property="IsTabStop" Value="False"/&gt;
    &lt;Setter Property="Margin" Value="6,2,6,2"/&gt;
    &lt;Setter Property="Template"&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType="controlsInputToolkit:Separator"&gt;
                &lt;Border
                    BorderThickness="{TemplateBinding BorderThickness}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    Background="{TemplateBinding Background}"
                    Height="1"/&gt;
            &lt;/ControlTemplate&gt;
        &lt;/Setter.Value&gt;
    &lt;/Setter&gt;
&lt;/Style&gt;</pre>
</div>
<h4>MenuItem Style</h4>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:d0da5a04-eff4-4c6b-b93e-b68154f08dad" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Style TargetType="controlsInputToolkit:MenuItem" x:Key="ZuneLikeMenuItem"&gt;
    &lt;Setter Property="Background" Value="Transparent"/&gt;
    &lt;Setter Property="FontSize" Value="14"/&gt;
    &lt;Setter Property="FontFamily" Value="Segoe UI, Tahoma, Arial"/&gt;
    &lt;Setter Property="BorderBrush" Value="Transparent"/&gt;
    &lt;Setter Property="BorderThickness" Value="0"/&gt;
    &lt;Setter Property="Padding" Value="8,2,10,2"/&gt;
    &lt;Setter Property="Template"&gt;
        &lt;Setter.Value&gt;
            &lt;ControlTemplate TargetType="controlsInputToolkit:MenuItem"&gt;
                &lt;Grid&gt;
                    &lt;VisualStateManager.VisualStateGroups&gt;
                        &lt;VisualStateGroup x:Name="CommonStates"&gt;
                            &lt;VisualState x:Name="Normal"/&gt;
                            &lt;VisualState x:Name="Disabled"&gt;
                                &lt;Storyboard&gt;
                                    &lt;DoubleAnimation Duration="0" Storyboard.TargetName="Presenter" Storyboard.TargetProperty="Opacity" To="0.5"/&gt;
                                &lt;/Storyboard&gt;
                            &lt;/VisualState&gt;
                        &lt;/VisualStateGroup&gt;
                        &lt;VisualStateGroup x:Name="FocusStates"&gt;
                            &lt;VisualState x:Name="Unfocused"/&gt;
                            &lt;VisualState x:Name="Focused"&gt;
                                &lt;Storyboard&gt;
                                    &lt;DoubleAnimation Duration="0" Storyboard.TargetName="Bg" Storyboard.TargetProperty="Opacity" To="1"/&gt;
                                    &lt;DoubleAnimation Duration="0" Storyboard.TargetName="IconPresenter" Storyboard.TargetProperty="Opacity" To="1"/&gt;
                                    &lt;DoubleAnimation Duration="0" Storyboard.TargetName="Presenter" Storyboard.TargetProperty="Opacity" To="1"/&gt;
                                &lt;/Storyboard&gt;
                            &lt;/VisualState&gt;
                        &lt;/VisualStateGroup&gt;
                    &lt;/VisualStateManager.VisualStateGroups&gt;
                    &lt;Rectangle
                        RadiusX="0"
                        RadiusY="0"
                        Fill="{TemplateBinding Background}"
                        Stroke="{TemplateBinding BorderBrush}"
                        StrokeThickness="{TemplateBinding BorderThickness}"/&gt;
                    &lt;Rectangle
                        x:Name="Bg"
                        RadiusX="0"
                        RadiusY="0"
                        StrokeThickness="0"
                        Opacity="0"
                        Fill="#11000000"/&gt;
                    &lt;Grid Margin="{TemplateBinding Padding}"&gt;
                        &lt;Grid.ColumnDefinitions&gt;
                            &lt;ColumnDefinition
                                Width="Auto"/&gt;
                            &lt;ColumnDefinition Width="2"/&gt;
                            &lt;ColumnDefinition Width="*"/&gt;
                            &lt;ColumnDefinition Width="17"/&gt;
                        &lt;/Grid.ColumnDefinitions&gt;
                        &lt;ContentPresenter
                            x:Name="IconPresenter"
                            Content="{TemplateBinding Icon}"
                            Margin="1"
                            Opacity=".7"
                            VerticalAlignment="Center"/&gt;
                        &lt;ContentPresenter
                            x:Name="Presenter"
                            MinWidth="120"
                            Opacity=".7"
                            Content="{TemplateBinding Header}"
                            ContentTemplate="{TemplateBinding HeaderTemplate}"
                            Grid.Column="2"/&gt;
                    &lt;/Grid&gt;
                &lt;/Grid&gt;
            &lt;/ControlTemplate&gt;
        &lt;/Setter.Value&gt;
    &lt;/Setter&gt;
&lt;/Style&gt;</pre>
</div>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/ZuneLikeContextMenuImplicitStyles.xaml_.txt"><strong>ZuneLikeContextMenuImplicitStyles.xaml.txt</strong></a><strong>:</strong> XAML. Download all three in one file. The file contains both implicit styles plus defined style names.</p>
<p>Here’s a comparison, a screenshot of the Zune menu on the left, and my Silverlight 4 context menu on the right:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="FinalContextMenus" border="0" alt="FinalContextMenus" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/FinalContextMenus.png" width="400" height="240" /> </p>
<p>Hope this helps you create some nice modern-looking Silverlight apps!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/zunelike-contextmenu-style/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Deep dive on Silverlight unit testing at Tech Ed next month</title>
		<link>http://www.jeff.wilcox.name/2010/05/silverlight-testing-at-teched-2010/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/silverlight-testing-at-teched-2010/#comments</comments>
		<pubDate>Tue, 11 May 2010 18:30:12 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TechEd]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/silverlight-testing-at-teched-2010/</guid>
		<description><![CDATA[Jeff Wilcox will be presenting a 200-level deep dive talk on Silverlight unit testing at the TechEd North America 2010 conference next month in New Orleans.]]></description>
			<content:encoded><![CDATA[<p>In about a month I will be presenting a 200-level session on Silverlight unit testing at <a href="http://northamerica.msteched.com/">Tech Ed North America in New Orleans</a>. The talk will be an hour with questions, so you can arrive new to Silverlight testing and leave with all the tools you need to be successful in building high-quality applications with the right level of regression coverage that your management can smile about.</p>
<p>The session will be more comprehensive than the overview talk I presented at <a href="http://www.jeff.wilcox.name/2010/03/mix10-testing-talk-online/">MIX 10 (which is available as a free online video stream now)</a>.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="TechEd_2010" border="0" alt="TechEd_2010" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/TechEd_2010.png" width="300" height="123" /> </p>
<p><a href="http://northamerica.msteched.com/topic/list?keyword=WEB205">Click here to view the talk information</a> on the Tech Ed site. The tentative information is as follows, but please double-check with the conference schedule builder before showing up:</p>
<blockquote><p><a href="http://northamerica.msteched.com/topic/list?keyword=WEB205"><strong>Unit Testing in Microsoft Silverlight</strong></a>       <br />Wednesday, June 9, 2010       <br />11:45 AM – 1:00 PM       <br />Room 287       <br />Session Code WEB205       <br /><a title="http://northamerica.msteched.com/topic/list?keyword=WEB205" href="http://northamerica.msteched.com/topic/list?keyword=WEB205">http://northamerica.msteched.com/topic/list?keyword=WEB205</a></p>
</blockquote>
<p>Hope to see some friendly faces in the audience! I’ll be up there in some sort of speaker polo shirt uniform with khakis, apparently this conference isn’t quite as trendy and cool as MIX in Vegas <img src='http://www.jeff.wilcox.name/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .</p>
<p>If you’re going to be attending Tech Ed, I’d appreciate any early comments you have as there is still time to shape the content of the talk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/silverlight-testing-at-teched-2010/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Silverlight Unit Test Framework: New version in the April 2010 Silverlight Toolkit</title>
		<link>http://www.jeff.wilcox.name/2010/05/new-2010-test-framework/</link>
		<comments>http://www.jeff.wilcox.name/2010/05/new-2010-test-framework/#comments</comments>
		<pubDate>Mon, 03 May 2010 22:26:06 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight Toolkit]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/05/new-2010-test-framework/</guid>
		<description><![CDATA[The latest release of the Silverlight Toolkit contains the new Silverlight Unit Test Framework, with a new modern user interface, out-of-browser support, and performance improvements.]]></description>
			<content:encoded><![CDATA[<p>In April we released a new version of the <a href="http://silverlight.codeplex.com/releases/view/43528">Silverlight Toolkit</a> for targeting Microsoft Silverlight 4. This release contains a new version of the Silverlight Unit Test Framework. Key improvements come in user interface, Silverlight 4 support, and performance.</p>
<h3>Rich, modern user interface</h3>
<p>The user interface no longer uses the antiquated HTML DOM bridge for displaying results, but now is a data bound, rich Silverlight application itself.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="NewTestFramework" border="0" alt="NewTestFramework" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/NewTestFramework.png" width="685" height="579" /></p>
<p>Rich results information is available, and a tree view control allows you to select results to be included in a test report that can be copied to the clipboard. Failures are automatically selected.</p>
<p>The results pane includes information about the tests that ran, as well as detailed information for failures.</p>
<p>Descriptive text helps identify negative tests, known test issues and bugs, and other important metadata that was not always exposed in the previous test framework.</p>
<h4>Integrated tag expression support</h4>
<p>The startup experience now allows you to enter a tag expression to select which tests to run, or not to run. You can add the Tag(“”) attribute to any test methods or classes to define your own tags. Also, the full and short names of tests and classes implicitly become test tags, as well as priorities.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="TagExpressionsEditor" border="0" alt="TagExpressionsEditor" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/05/TagExpressionsEditor.png" width="685" height="375" /> </p>
<p>This means that you can define tags such as:</p>
<table border="0" cellspacing="0" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="152">!MyTest1</td>
<td valign="top" width="448">Run all tests except for the method named MyTest1</td>
</tr>
<tr>
<td valign="top" width="152">MyTest1+MyTest2</td>
<td valign="top" width="448">Run the MyTest1 and MyTest2 test methods</td>
</tr>
</tbody>
</table>
<h3>Out of Browser support</h3>
<p>The framework now supports running out-of-browser. Paired with the new Silverlight 4 Tools for Visual Studio 2010, you can press F5 to run a test project you have marked as an out-of-browser.</p>
<p>This also opens up an opportunity to do testing of elevated apps that make use of AutomationFactory and other advanced features on Windows.</p>
<h3>Simplified dependencies</h3>
<p>The test framework removed dependencies on System.Windows.Browser (from the platform) and System.Xml.Linq (XLinq, from the SDK).</p>
<h3>Building blocks for Windows Phone testing support</h3>
<p>This version also contains the full source to the phone testing interface, which is significantly different in visual design and experience to coincide with the Windows Phone device size.</p>
<p>However, the story for phone testing is still developing: in the meantime binaries designed for phone use can be found at <a href="http://jeffatmix.com/">http://jeffatmix.com/</a> </p>
<h3>New location for binaries</h3>
<p>Since the new rich user interface contains a number of controls, the traditional design-time integration system conflicts and presents some issues.</p>
<p>As a result, we had to move the binaries from the Bin directory of the toolkit installation folder into a new Testing directory.</p>
<p>So the two test framework assemblies (Microsoft.Silverlight.Testing and Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight) have moved.</p>
<p>This location change could cause existing applications that reference the test assemblies to fail to compile due to the &quot;missing&quot; references.</p>
<p>If that happens, please delete the two broken references and create references to these assemblies in their new location. Everything else should continue to work as expected.</p>
<h3>Simplified test project template</h3>
<p>In alignment with the test project changes in Visual Studio 2010, which are more simplified, the unit test project template for Silverlight no longer includes a README.TXT file.</p>
<h3>Known issues</h3>
<h5>Test service</h5>
<p>I’ve received reports from a number of people about issues with the test service automation support. Some of the NDA/preview users of the framework reported issues that were corrected, but there may still be some bugs out there. I’m working to investigate and post a fix if and when I know more.</p>
<p>In the meantime I know that <a href="http://statlight.net/">StatLight</a>, a third party system, has been updated for the April release and is working well for automation.</p>
<h5>Test panel and visuals</h5>
<p>Please beware that some of your tests may need to be updated to use the new framework if your application, utility functions, or tests ever used the Application.Current.RootVisual (against the recommended pattern for interface testing).</p>
<p>The root visual is now the test framework application runner itself, and the tests run within the same TestPanel as before. Controls added to the test panel will not be located at the 0, 0 screen position, but likely near the bottom of the screen instead.</p>
<p>Hope this helps. To get started, download and install the April toolkit!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/05/new-2010-test-framework/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Property change notifications for multithreaded Silverlight applications</title>
		<link>http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/</link>
		<comments>http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 18:27:28 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[silverlight;data binding;threading]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/</guid>
		<description><![CDATA[Jeff Wilcox introduces a base class for dealing with INotifyPropertyChanged classes that is safe to use from background threads in Silverlight and Windows Phone.]]></description>
			<content:encoded><![CDATA[<p>As I’ve been developing more complex Silverlight business applications, I’ve been increasingly relying on <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.95).aspx">BackgroundWorker</a> to offload complex calculations and operations to the background thread.</p>
<p>Something I didn’t have to worry about in the typical user interface thread-only implementation of my app was which thread change notifications fire on.</p>
<p>Here’s a typical scenario:</p>
<ol>
<li>You have a CLR property on a data/model object in your app. In a background thread, the property is updated.</li>
<li>As all data and model objects should be, the type implements <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(VS.95).aspx">INotifyPropertyChanged</a> (the data binding system relies on this to know when to update bindings).</li>
<li>The property changed event is fired, and listeners react to the change, including the data binding system.</li>
<li>The data binding system throws an invalid cross thread exception, since all UI operations, including handing off the binding changes, need to happen on the UI thread (but it’s happening on a background thread)</li>
</ol>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/BackgroundThreadWithoutDispatcher.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="BackgroundThreadWithoutDispatcher" border="0" alt="BackgroundThreadWithoutDispatcher" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/BackgroundThreadWithoutDispatcher_thumb.png" width="685" height="160" /></a> </p>
<p>So what you really need to do is funnel those change notifications back to always happen on the user interface thread – that’s what makes the most sense given the data binding requirement.</p>
<p>By using a dispatcher, which can accept a BeginInvoke for that other thread, it will all just work and binding will move along happily:</p>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/BackgroundThreadWithDispatcher.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="BackgroundThreadWithDispatcher" border="0" alt="BackgroundThreadWithDispatcher" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/BackgroundThreadWithDispatcher_thumb.png" width="685" height="160" /></a> </p>
<p>This scenario is ripe for a few helper classes that I’m open to receiving feedback on. Hope you agree with my approach of using a ‘smart dispatcher’.</p>
<h2>One Dispatcher to rule them all</h2>
<p>The only thing you need to fire an Action on the primary UI thread is a reference to a <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(VS.95).aspx">Dispatcher</a> instance. Unfortunately this isn’t something you can request from a background thread – you need to have the instance already stored away in most cases.</p>
<p>As a result, I’ve a static helper class and in it, I try and make sure that there is an instance stored before any of my data binding or model code is used.</p>
<p>Though I could have used <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx">SynchronizationContext</a> instead, Dispatcher is a little easier to use, and better suited to WPF and Silverlight apps.</p>
<p>In my App.xaml.cs, I add a line that calls Initialize on my class. This is to make sure that there is <em>always</em> an available dispatcher for other threads to get access to:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:80de451c-9a3a-4b80-aa15-24fd2bf7890d" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">public App()
{
    this.Startup += this.Application_Startup;
    this.Exit += this.Application_Exit;
    this.UnhandledException += this.Application_UnhandledException;

    SmartDispatcher.Initialize(Deployment.Current.Dispatcher);

    InitializeComponent();
}</pre>
</div>
<p>If you didn’t want to have to add this code to initialization, my implementation of a dispatcher helper class falls back to trying to grab the dispatcher from the root visual – but this won’t work in all scenarios, so I prefer the above. One more thing to remember however.</p>
<h2>Being smart about using the dispatcher</h2>
<p>It’s easy enough to replace all event firings for property changes to go through the dispatcher. However, this will reduce performance some; instead of the call being made immediately, it’s made at a later time.</p>
<p>There is a hidden method called <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.checkaccess(v=VS.95).aspx">CheckAccess</a> on Dispatcher that returns true if you are on the same thread that the Dispatcher was first created in. By checking with it before making a call, we can make a better perf choice:</p>
<ul>
<li>If CheckAccess is true and we’re on the UI thread, just go ahead and directly invoke the Action. </li>
<li>Else, BeginInvoke with the Dispatcher that will take care of getting it done on the UI thread later. </li>
</ul>
<p>I’ve also done some optimization to try and ensure that the design-time experience at least stays consistent. In general you shouldn’t have background operations ever occurring in a design-time scenario.</p>
<p>The static helper class I’ve created is called <strong>SmartDispatcher</strong> and simplifies all of this logic.</p>
<p>So here’s my smart dispatcher implementation:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:5f822523-5e30-4745-9db5-23a523f087b5" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.ComponentModel;

namespace System.Windows.Threading
{
    /// &lt;summary&gt;
    /// A smart dispatcher system for routing actions to the user interface
    /// thread.
    /// &lt;/summary&gt;
    public static class SmartDispatcher
    {
        /// &lt;summary&gt;
        /// A single Dispatcher instance to marshall actions to the user
        /// interface thread.
        /// &lt;/summary&gt;
        private static Dispatcher _instance;

        /// &lt;summary&gt;
        /// Backing field for a value indicating whether this is a design-time
        /// environment.
        /// &lt;/summary&gt;
        private static bool? _designer;

        /// &lt;summary&gt;
        /// Requires an instance and attempts to find a Dispatcher if one has
        /// not yet been set.
        /// &lt;/summary&gt;
        private static void RequireInstance()
        {
            if (_designer == null)
            {
                _designer = DesignerProperties.IsInDesignTool;
            }

            // Design-time is more of a no-op, won't be able to resolve the
            // dispatcher if it isn't already set in these situations.
            if (_designer == true)
            {
                return;
            }

            // Attempt to use the RootVisual of the plugin to retrieve a
            // dispatcher instance. This call will only succeed if the current
            // thread is the UI thread.
            try
            {
                _instance = Application.Current.RootVisual.Dispatcher;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("The first time SmartDispatcher is used must be from a user interface thread. Consider having the application call Initialize, with or without an instance.", e);
            }

            if (_instance == null)
            {
                throw new InvalidOperationException("Unable to find a suitable Dispatcher instance.");
            }
        }

        /// &lt;summary&gt;
        /// Initializes the SmartDispatcher system, attempting to use the
        /// RootVisual of the plugin to retrieve a Dispatcher instance.
        /// &lt;/summary&gt;
        public static void Initialize()
        {
            if (_instance == null)
            {
                RequireInstance();
            }
        }

        /// &lt;summary&gt;
        /// Initializes the SmartDispatcher system with the dispatcher
        /// instance.
        /// &lt;/summary&gt;
        /// &lt;param name="dispatcher"&gt;The dispatcher instance.&lt;/param&gt;
        public static void Initialize(Dispatcher dispatcher)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            _instance = dispatcher;

            if (_designer == null)
            {
                _designer = DesignerProperties.IsInDesignTool;
            }
        }

        /// &lt;summary&gt;
        ///
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static bool CheckAccess()
        {
            if (_instance == null)
            {
                RequireInstance();
            }

            return _instance.CheckAccess();
        }

        /// &lt;summary&gt;
        /// Executes the specified delegate asynchronously on the user interface
        /// thread. If the current thread is the user interface thread, the
        /// dispatcher if not used and the operation happens immediately.
        /// &lt;/summary&gt;
        /// &lt;param name="a"&gt;A delegate to a method that takes no arguments and
        /// does not return a value, which is either pushed onto the Dispatcher
        /// event queue or immediately run, depending on the current thread.&lt;/param&gt;
        public static void BeginInvoke(Action a)
        {
            if (_instance == null)
            {
                RequireInstance();
            }

            // If the current thread is the user interface thread, skip the
            // dispatcher and directly invoke the Action.
            if (_instance.CheckAccess() || _designer == true)
            {
                a();
            }
            else
            {
                _instance.BeginInvoke(a);
            }
        }
    }
}</pre>
</div>
<h2>A property change base class</h2>
<p>Next up, instead of having to manually wire up the INotifyPropertyChanged interface in all my data classes, I prefer to derive from a common base class, PropertyChangedBase, that has logic in it to use my smart dispatcher.</p>
<p>This base class:</p>
<ul>
<li>Has a protected NotifyPropertyChanged method that does all the real work</li>
<li>Statically stores created event arguments to improve performance over time (only one PropertyChangedEventArgs instance is required per property name in the application’s lifetime)</li>
<li>Uses SmartDispatcher to use a dispatcher only if not running on the user interface thread, otherwise directly invokes the property change handler.</li>
</ul>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:081eec95-108d-4637-bc82-a9dc32c0de06" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.Windows.Threading;

namespace System.ComponentModel
{
    /// &lt;summary&gt;
    /// A base class for data objects that implement the property changed
    /// interface, offering data binding and change notifications.
    /// &lt;/summary&gt;
    public class PropertyChangedBase : INotifyPropertyChanged
    {
        /// &lt;summary&gt;
        /// A static set of argument instances, one per property name.
        /// &lt;/summary&gt;
        private static Dictionary&lt;string, PropertyChangedEventArgs&gt; _argumentInstances = new Dictionary&lt;string, PropertyChangedEventArgs&gt;();

        /// &lt;summary&gt;
        /// The property changed event.
        /// &lt;/summary&gt;
        public event PropertyChangedEventHandler PropertyChanged;

        /// &lt;summary&gt;
        /// Notify any listeners that the property value has changed.
        /// &lt;/summary&gt;
        /// &lt;param name="propertyName"&gt;The property name.&lt;/param&gt;
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("PropertyName cannot be empty or null.");
            }

            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                PropertyChangedEventArgs args;
                if (!_argumentInstances.TryGetValue(propertyName, out args))
                {
                    args = new PropertyChangedEventArgs(propertyName);
                    _argumentInstances[propertyName] = args;
                }

                // Fire the change event. The smart dispatcher will directly
                // invoke the handler if this change happened on the UI thread,
                // otherwise it is sent to the proper dispatcher.
                SmartDispatcher.BeginInvoke(delegate
                {
                    handler(this, args);
                });
            }
        }
    }
}</pre>
</div>
<h2>Putting it all together</h2>
<p>To use this in your own application, you take your model/data classes and derive from PropertyChangedBase. Then, in CLR setters, always call NotifyPropertyChanged:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:dc14a951-f0ec-424e-a0a3-da3b76cbeada" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">public class SampleData : PropertyChangedBase
{
    private string _someText;
    public string SomeText
    {
        get { return _someText; }
        set
        {
            _someText = value;
            NotifyPropertyChanged("SomeText");
        }
    }
}</pre>
</div>
<h2>Grab the code</h2>
<p>I’ve decided to place these classes inside their appropriate system namespaces: System.Windows.Threading for the smart dispatcher, and System.ComponentModel for the PropertyChangedBase. Hope that isn’t too offensive.</p>
<p>Here are the files for download as well:</p>
<ul>
<li><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/PropertyChangedBase.cs_.txt">PropertyChangedBase.cs</a></li>
<li><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/SmartDispatcher.cs_.txt">SmartDispatcher.cs</a></li>
</ul>
<p>Hope this helps. Let me know what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Template parts and custom controls (quick tip)</title>
		<link>http://www.jeff.wilcox.name/2010/04/template-part-tips/</link>
		<comments>http://www.jeff.wilcox.name/2010/04/template-part-tips/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 00:40:57 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight; Controls; Tips]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/04/template-part-tips/</guid>
		<description><![CDATA[Here’s a few simple tips and recommendations when developing custom Silverlight controls, as it relates to template parts. What’s with all the control development tips? We’re looking at the best way to share a lot of the ‘black magic’ of control development with the community, and will have details on that another way – today [...]]]></description>
			<content:encoded><![CDATA[<p>Here’s a few simple tips and recommendations when developing custom Silverlight controls, as it relates to template parts.</p>
<p><strong>What’s with all the control development tips?</strong></p>
<p>We’re looking at the best way to share a lot of the ‘black magic’ of control development with the community, and will have details on that another way – today so much of this information is hidden away in blog posts like this one.</p>
<p>Hopefully we’ll have a whitepaper at some point.</p>
<h3>What are template parts?</h3>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="TemplateBinding" border="0" alt="TemplateBinding" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/04/TemplateBinding.png" width="576" height="216" /> </p>
<p>Visualizing a control and it’s expected template: “MyControl” has a template part called Button, of type ButtonBase. And although it also may contain a text box, no events from the text box are used. Instead, just a template binding to the Text property.</p>
<p>This control has 1 template part: Button, not two. Don’t be tempted to have a text box template part!</p>
<h3>Do you need template parts or not?</h3>
<p>It’s important to minimize the number of template parts in a control to reduce complexity. Over-engineering controls leads to reduced code quality, expensive control maintenance, and increased testing cost.</p>
<p>If you can expose dependency properties and template bind into those properties from controls in the template, there is absolutely no reason to have parts present.</p>
<p>If you need to hook up to events of anything in the template, it’s likely that you will need to have a part for that sub control.</p>
<p>Choose wisely.</p>
<h3>Use constants for the names</h3>
<p>To prevent potential spelling errors or simple mistakes, it’s a good idea to not hard-code the template part name anywhere in your control.</p>
<p>Instead, add a constant string to the top of the file with the part name. You can then refer to it in the OnApplyTemplate method, the template part attribute, and anywhere else it is needed.</p>
<p>The constant can be protected if a subclass may want to reuse the name.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:56a12f0a-8e04-429f-abdb-294f6ea8028a" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">private const string PartButtonName = "Button";</pre>
</div>
<h3>Store parts as private fields in your class</h3>
<p>Template parts are not designed to always be inherited by any subclasses. Though the subclasses are welcome to use the same parts, they should not expect to just use the base classes: they need to use OnApplyTemplate to also grab instances of the parts.</p>
<p>So do use <strong>private fields </strong>to store the parts in the OnApplyTemplate method:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:1ca18128-2e4c-4831-903f-778ef6d4a6bd" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">private ButtonBase _button;</pre>
</div>
<h3>Detach any existing event handlers in OnApplyTemplate</h3>
<p>Controls can be restyled and retemplated as a result. Make sure to detach any event handlers from previous template parts before adding new handlers.</p>
<p>Here’s the typical pattern for that:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:097f53b0-9ab5-4d2e-a0fd-eab5b6785bac" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    if (_button != null)
    {
        _button.Click -= OnButtonClick;
    }

    _button = GetTemplateChild(PartButtonName) as ButtonBase;

    if (_button != null)
    {
        _button.Click += OnButtonClick;
    }
}</pre>
</div>
<h3>Don’t assume template parts exist</h3>
<p>Whenever using template parts in your code, you should not assume that they exist. Always check for null, and unless a significant reason exists for requiring their presence, never throw an error in this condition.</p>
<p>Often code in the class relating to states and properties will execute long before the template is applied, yielding no template part instances early on.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:9a49b70a-8e0f-45d5-a1d7-3c6d32e5c1b5" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">if (_button != null)
{
   // Do something with the button
}</pre>
</div>
<h3>Mark controls with template part attributes</h3>
<p>Design surfaces like Expression Blend expect that controls are marked with the template part attributes. These are required to provide helpful tooling for editing templates.</p>
<p>Make sure to use the constant template part name that you created a few tips ago:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:d7b145d3-c7c4-4565-bc51-e0f5703d48aa" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">[TemplatePart(Name = PartButtonName, Type = typeof(ButtonBase))]
public partial class MyControl : ContentControl
{
}</pre>
</div>
<h3>Template parts don’t necessarily inherit from their base class</h3>
<p>It’s possible to have different template parts at each level of a control’s hierarchy. It’s even possible that subclasses may not want to use a template of a base class.</p>
<p>As a result, <strong>never</strong> provide template parts as public or protected properties on your controls. If subclasses want them, they can ask for them.</p>
<p>This is another reason it’s important to quietly check template parts for null, they may not be defined in base classes.</p>
<p>You should define template part attributes on every subclasses where expected. They do not inherit.</p>
<p>Hope this helps.</p>
<h5>Other tips</h5>
<p>David Anson has been furiously writing tips as well as we all have hallway conversations on control development: Check out:</p>
<ul>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/30/sometimes-you-just-gotta-do-the-best-you-can-tip-read-only-custom-dependencyproperties-don-t-exist-in-silverlight-but-can-be-closely-approximated.aspx">Read-only dependency properties in Silverlight</a></li>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/29/that-s-why-it-s-called-the-default-value-instead-of-default-values-tip-the-default-value-of-a-dependencyproperty-is-shared-by-all-instances-of-the-class-that-registers-it.aspx">Default values for dependency properties</a></li>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/26/when-you-have-two-good-options-go-with-the-easier-one-tip-set-dependencyproperty-default-values-in-a-class-s-default-style-if-it-s-more-convenient.aspx">Style default values if needed</a></li>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/25/the-platform-giveth-power-don-t-taketh-it-away-tip-do-not-assign-dependencyproperty-values-in-a-constructor-it-prevents-users-from-overriding-them.aspx">Don’t use the constructor to set defaults</a></li>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/24/freedom-isn-t-free-tip-when-creating-a-dependencyproperty-follow-the-handy-convention-of-wrapper-register-static-virtual.aspx">How to define dependency properties</a></li>
<li><a href="http://blogs.msdn.com/delay/archive/2010/03/23/do-one-thing-and-do-it-well-tip-the-clr-wrapper-for-a-dependencyproperty-should-do-its-job-and-nothing-more.aspx">When using dependency properties, the CLR setters and getters must be super simple</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/04/template-part-tips/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Silverlight 4: New parser implementation. New parser features.</title>
		<link>http://www.jeff.wilcox.name/2010/03/silverlight4-new-parser/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/silverlight4-new-parser/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 22:56:12 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[silverlight; parser]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/silverlight4-new-parser/</guid>
		<description><![CDATA[Buttons with direct content. Better error messages. Designers and developers will like the new parser implementation in Silverlight 4.]]></description>
			<content:encoded><![CDATA[<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="XamlNewFeatures" border="0" alt="XamlNewFeatures" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/XamlNewFeatures.png" width="685" height="28" /> </p>
<p><a href="http://www.flickr.com/photos/lara604/2369412952/"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="Designers wear black turtlenecks. Photo by Lara604 - http://www.flickr.com/photos/lara604/2369412952/ (creative commons)" border="0" alt="Designers wear black turtlenecks. Photo by Lara604 - http://www.flickr.com/photos/lara604/2369412952/ (creative commons)" align="right" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/XamlLimitations.png" width="350" height="281" /></a> XAML is such an important thing for enabling modern user interfaces that it’s easy to forget how complex and integral the parser is to the Silverlight platform.</p>
<p>It’s the thing that lets us geek out in code when we need to, yet still talk to our designer friends who wear black turtlenecks, dream in Adobe Illustrator actions, and love Expression Blend.</p>
<p>Your designer friends are going to like Silverlight 4 more than Silverlight 3, thanks to new features like direct content.</p>
<p>Developers are going to like Silverlight 4 more, since there are new, better error messages both while using Visual Studio, and at runtime. This means fewer <a href="http://www.bing.com/search?q=Silverlight+AG_E_UNKNOWN">AG_E_UNKNOWN errors</a>.</p>
<h2>What’s new?</h2>
<p>In Silverlight 4, more than a year of development went into a modern, improved parser to offer new XAML features, fix some common requests and complaints, and develop a modern platform for future parser improvements to build upon.</p>
<p>A number of expert engineers at Microsoft came together to make this possible, and hopefully you’ll find the improvements worthwhile.</p>
<p>In no particular order, and not necessarily exhaustive, here’s a look at some of the changes (more comprehensive information in <a href="http://www.davidpoll.com/2010/03/15/new-in-the-silverlight-4-rc-xaml-features/">David Poll’s similar blog post</a>).</p>
<h3>Whitespace treatment</h3>
<p>XAML in Silverlight 4 is parsed as you’d expect for XML in general: newlines, for instance, don’t show up unless you add the xml:space=’preserve’ attribute first.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:c9caf72d-2517-4c96-a327-fe3cc6edae67" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;StackPanel Orientation="Horizontal"&gt;
    &lt;TextBlock&gt;
       &lt;TextBlock.Text&gt;
          This is the first line of the text block,
          and this is still the first line.
       &lt;/TextBlock.Text&gt;
    &lt;/TextBlock&gt;
    &lt;TextBlock xml:space="preserve"&gt;
       &lt;TextBlock.Text&gt;
          This is the first line of the text block,
          and this is the second line.
       &lt;/TextBlock.Text&gt;
    &lt;/TextBlock&gt;
&lt;/TextBlock&gt;</pre>
</div>
<p><strong>Upgrade warning: </strong>This change is double-edged. When we moved the Silverlight Toolkit samples to use the new parser, we were bit by the source code that displays in the source viewer: it was all one line! The preservation line had to be added, since previously we depended on the parser just grabbing and using the newlines from the parser input for breaks in the text boxes.</p>
<h3>Direct content</h3>
<p>Buttons work better now. You couldn’t do this before:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:70aae754-352e-48b4-b8f6-387c0353b5c6" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Button&gt;Ok&lt;/Button&gt;</pre>
</div>
<h3>Error messages</h3>
<p>Many, many bugs around error message handling have been fixed thanks to the new parser’s error service implementation. In most situations, errors are more descriptive, similar to their WPF counterparts, and will contain useful line and column number information.</p>
<p>In Silverlight 3, many times XAML parsing problems resulted in errors being identified as being at line 0, column 0, and those days are mostly over.</p>
<h3>Dictionaries done right</h3>
<p>If a type or property implements IDictionary, you can now use x:Key to add entries into dictionaries. <em>Note</em> that we’re talking about the non-generic IDictionary interface.</p>
<h3>ISupportInitialize</h3>
<p>A feature WPF developers have enjoyed, begin and end initialization calls are made before and after properties are defined in XAML.</p>
<h3>Template bindings require CLR getters and setters</h3>
<p>Dependency properties must have defined CLR getters and settings to be used in template bindings, consistent with WPF.</p>
<h3>XmlnsDefinitionAttribute</h3>
<p>Especially when using the Silverlight Toolkit and other control libraries, you needed to define a new XMLNS definition in every page, for every assembly you wanted to use.</p>
<p>xmlns:controlsToolkit=”…”, xmlns:navigation=”…”, etc.</p>
<p>Now with <a href="http://msdn.microsoft.com/en-us/library/system.windows.markup.xmlnsdefinitionattribute.aspx">XmlnsDefinitionAttribute</a> (an assembly-level attribute) support, you often can get by with less. All the assemblies in a single product can share a namespace which you can then just define one time.</p>
<h3>x:Uid support</h3>
<p>Uids are better supported, paving the way for localization tools and other uses of <a href="http://msdn.microsoft.com/en-us/library/bb613571.aspx">x:Uid</a>.</p>
<h3>Root default namespace restriction removed</h3>
<p>Prior to Silverlight 4, the root XAML namespace had to be one of the supported standard namespaces. This restriction is removed. Note that you still need it if you want to reference set properties that come from the core Silverlight elements.</p>
<h2>What about backward compatibility?</h2>
<p>Compatibility with previous versions of Silverlight is one of the most important goals for the development and test teams working on Silverlight. As a result, there are a fair number of “quirks mode” checks throughout the codebase.</p>
<p>Whenever a bug fix or new feature is implemented, a quirks mode check often needs to be inserted to maintain the previous codepaths for compatibility reasons.</p>
<p>It’s a good technical challenge, and though “quirking” probably has a bad reputation from the Internet Explorer 5 &amp; 6 days, it really does work well in Silverlight.</p>
<h3>Dual parser implementations</h3>
<p>Beyond just quirks mode checks in the Silverlight runtime, we have decided to also include the Silverlight 3 parser inside of Silverlight 4 for compatibility reasons.</p>
<p>At the start of the code path that parses XAML and eventually returns an object or tree, there’s an if/else check that keeps the parser versions completely separate:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:70b52b1a-1d05-448a-9f8c-170dc7bae926" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">    if (CQuirksMode::ShouldUseSL3Parser(pCore))
    {
        // ... Old parser code path
    }
    else
    {
        // ... New, awesome parser code path
    }</pre>
</div>
<p>And the underlying quirks mode check whether the application’s major version is less than 4.</p>
<h3>Which parser will be used?</h3>
<p>The <strong>target application’s Silverlight runtime version</strong> is what determines which parser will be used at runtime. This value gets placed inside of the application manifest XAML file, in the application’s .Xap, at build time.</p>
<p>If you examine a .Xap file (rename to .Zip, extract the contents), inside the root directory you will find a file named AppManifest.xaml.</p>
<p>In the Deployment element there is an attribute called RuntimeVersion. This needs to start with 4.0 to use the new parser, such as:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:1afce63e-d1e9-4770-8ba5-d7d3c2649e41" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Deployment
    xmlns="http://schemas.microsoft.com/client/2007/deployment"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    EntryPointAssembly="SilverBugger"
    EntryPointType="JeffWilcox.SilverBugger.App"
    RuntimeVersion="4.0.50303.0" /&gt;</pre>
</div>
<p><em>Note that I’ve removed the rest of the file contents for brevity.</em></p>
<p>This means that control and component developers need to be aware of this for new controls: if you have a control whose default styles and templates expect the Silverlight 4 XAML parser to be used (if you’re using direct Button content, for example), then you need to make sure your customers only use those components with Silverlight 4 applications.</p>
<h2>What about System.Xaml?</h2>
<p>System.Xaml shipped with WPF 4, and is a modern managed XAML parser implementation. We had signifcant knowledge and code sharing on the team to make sure that the implementations were similar, common, and yet they are different.</p>
<p>The parser in Silverlight is a complex implementation because it often has to bridge the native/managed code gap: so much of the core Silverlight runtime is implemented in native code, so properties and other information need to be shared between the two.</p>
<p>Though this is not a technical discussion of the implementation, I will note that there is a crisp interface shared by both a XamlNativeRuntime and XamlManagedRuntime, and it’s pretty impressive.</p>
<p><em>Let me know how your experiences are with the new Silverlight 4 parser.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/silverlight4-new-parser/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>&#8220;Peppermint&#8221; MIX demo sources</title>
		<link>http://www.jeff.wilcox.name/2010/03/peppermint-src/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/peppermint-src/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 21:30:53 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MIX]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/peppermint-src/</guid>
		<description><![CDATA[At MIX, during my talk on unit testing Silverlight and Windows Phone applications, I demoed a simple application called ‘Peppermint’. Here’s the source; I’ll be writing up a full tutorial on Windows Phone later, so these are just ‘bleeding-edge bits’. Peppermint-Demo.zip [Zip, 1.2 MB] Silverlight: Requires Visual Studio 2010 (or express) Requires the Silverlight Toolkit [...]]]></description>
			<content:encoded><![CDATA[<p>At MIX, during my talk on <a href="http://live.visitmix.com/MIX10/Sessions/CL59">unit testing Silverlight and Windows Phone applications</a>, I demoed a simple application called ‘Peppermint’. Here’s the source; I’ll be writing up a full tutorial on Windows Phone later, so these are just ‘bleeding-edge bits’.</p>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/Peppermint-Demo.zip"><strong>Peppermint-Demo.zip</strong></a> [Zip, 1.2 MB]</p>
<p>Silverlight:</p>
<blockquote><p>Requires Visual Studio 2010 (or express)     <br />Requires the <a href="http://silverlight.codeplex.com/">Silverlight Toolkit</a>      <br />Requires the test framework binaries included in the zip</p>
</blockquote>
<p>Windows Phone:</p>
<blockquote><p>Requires the <a href="http://www.silverlight.net/getstarted/devices/windows-phone/">Windows Phone development tools CTP</a>      <br />Requires the test framework binaries included in the zip</p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/peppermint-src/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Displaying 2D QR barcodes in Windows Phone applications</title>
		<link>http://www.jeff.wilcox.name/2010/03/windowsphone-barcode/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/windowsphone-barcode/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 18:37:51 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/windowsphone-barcode/</guid>
		<description><![CDATA[Last year, enthused by the Starbucks Mobile Card application for the iPhone, I built an app that displays 2D QR barcodes in Silverlight. Today, in two minutes, I got that running on the Windows Phone. Talk about an awesome development experience. These barcode-displaying apps let you get rid of the plastic in your wallet and [...]]]></description>
			<content:encoded><![CDATA[<p>Last year, enthused by the <a href="http://www.techflash.com/seattle/2009/09/starbucks_debuts_apps_for_finding_stores_buying_coffee.html">Starbucks Mobile Card</a> application for the iPhone, I <a href="http://www.jeff.wilcox.name/2009/09/quick-read-silverlight-barcodes/">built an app that displays 2D QR barcodes in Silverlight</a>. Today, in two minutes, I got that running on the Windows Phone. Talk about an awesome development experience.</p>
<p>These barcode-displaying apps let you get rid of the plastic in your wallet and use your phone instead. Many airports and carriers have been using these barcodes for <a href="http://www.tsa.gov/approach/tech/paperless_boarding_pass_expansion.shtm">paperless boarding passes</a>, too.</p>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/CoffeeCardApps.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="CoffeeCardApps" border="0" alt="CoffeeCardApps" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/CoffeeCardApps_thumb.png" width="624" height="496" /></a>     <br /><em>The barcode within the Windows Phone app on the left is QR encoded and stores the text ‘Hello World’</em></p>
<p>So, background: when I did this first implementation in September of ‘09, I wanted to see how quickly I could adapt existing .NET libraries for the desktop to work with Silverlight. I was really happy to find that it was simple, taking an existing .NET library for generating <a href="http://en.wikipedia.org/wiki/QR_Code">2D QR barcodes</a> and doing some <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap(VS.95).aspx">WriteableBitmap</a> work.</p>
<p>This really demonstrates how awesome the app platform for the Windows Phone can be – building on top of not only existing Silverlight knowledge, code, and libraries – but also full-fledged .NET libraries.</p>
<p>Here’s the app, and you’ll even see on the design surface that the barcode is showing up in real-time:</p>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/BarcodeInVs.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="BarcodeInVs" border="0" alt="BarcodeInVs" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/BarcodeInVs_thumb.png" width="685" height="600" /></a> </p>
<p>I expose the barcode through a simple control. Here’s the XAML that binds the barcode’s encoded text to the text box’s text – yes, you can type on the phone in real-time and watch the barcode update:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:63d8c26a-a66c-47f6-b38c-810a423bf6b4" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;barcode:QuickReadBarcode
    Width="100"
    Background="White"
    Text="{Binding Path=Text, ElementName=dataText}" /&gt;</pre>
</div>
<h4>Download the source to this Windows Phone app</h4>
<p><a href="http://media.jeff.wilcox.name/blog/barcode/JeffWilcox.WindowsPhone.Barcode.zip">JeffWilcox.WindowsPhone.Barcode.zip</a> [Zip, 1.12 MB]</p>
<p>Requires the Windows Phone development tools CTP (<a href="http://www.silverlight.net/getstarted/devices/windows-phone/">info</a>)</p>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/windowsphone-barcode/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Data binding user settings in Windows Phone applications</title>
		<link>http://www.jeff.wilcox.name/2010/03/data-binding-user-settings-in-windows-phone-applications/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/data-binding-user-settings-in-windows-phone-applications/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 01:02:23 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/data-binding-user-settings-in-windows-phone-applications/</guid>
		<description><![CDATA[Thanks to the rich data binding system built into Silverlight for Windows Phone, you can easily store rich user settings without using code behind files. The canonical example of user settings is a “Show this welcome screen at startup” checkbox so that your application can offer a nice out-of-box experience. By writing a simple type [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to the rich data binding system built into <a href="http://www.silverlight.net/getstarted/devices/windows-phone/">Silverlight for Windows Phone</a>, you can easily store rich user settings without using code behind files.</p>
<p><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/StartupPage1.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="StartupPage" border="0" alt="StartupPage" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/StartupPage_thumb1.png" width="301" height="589" /></a> </p>
<p>The canonical example of user settings is a “Show this welcome screen at startup” checkbox so that your application can offer a nice out-of-box experience.</p>
<p>By writing a simple type with some properties, adding a few helper files, and setting up a two-way data binding, you can store any settings without having to write special code.</p>
<p>Here’s what the completed project’s two-way data binding looks like for the checkbox shown to the right:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:31a809df-3c54-45c6-9f71-e3939f303551" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;CheckBox
   IsChecked="{Binding Source={StaticResource MySettings}, Path=IsFirstRun, Mode=TwoWay}"
   Content="Show this page at startup"
/&gt;</pre>
</div>
<p>You’ll see these components in the data binding:</p>
<ul>
<li>Source is a static resource, a strongly typed settings class you define</li>
<li>Path points to the property name to bind to</li>
<li>Binding is two-way so that the value is stored automatically</li>
<li>Value and type converters can be applied as always in bindings if necessary</li>
</ul>
<p>Let’s quickly implement this functionality in a quick app. We’ll also add a text box to the main application page, to let the value always be persisted between application runs, and even application updates.</p>
<h3>Getting started</h3>
<p>You can use the free <a href="http://www.silverlight.net/getstarted/devices/windows-phone/">Windows Phone development tools</a>, or just Visual Studio 2010 if you have the phone tools CTP installed already.</p>
<p>Create a new ‘Silverlight for Windows Phone’ application project.</p>
<h3>Adding some helper code</h3>
<p>Either add the class library project I have for download here, or just add the 4 C# files that make up the helper code:</p>
<ul>
<li><a href="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/SettingsHelperCode.zip"><strong>SettingsHelperCode.zip</strong></a> (8 KB, zip)</li>
</ul>
<h3>Creating your configuration/settings type</h3>
<p>Next, we need to create a strongly typed configuration class that derives from my SettingsProvider type. This class must:</p>
<ul>
<li>Implement INotifyPropertyChanged, so that bindings work well</li>
<li>Have properties of the appropriate type for the settings you are interested in. Optionally, include the DefaultValue attribute to provide defaults.</li>
</ul>
<p>Here is the MySettings.cs file I’ve created for this app. It defines two properties that I always want to have stored:</p>
<ul>
<li><strong>HelloWorld</strong> is just some text I let the user edit in the user interface. A more realistic setting might be “best friend” or a list of people to show on the home screen of the app.</li>
<li><strong>IsFirstRun</strong> is a true/false value that indicates whether the welcome screen should be shown.</li>
</ul>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:f4b3a428-cf5a-4044-bad1-2a305d70a31b" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.ComponentModel;
using JeffWilcox.Settings;

namespace Sample
{
    /// &lt;summary&gt;
    /// My settings class for storing application data and setting specific to
    /// the user.
    /// &lt;/summary&gt;
    public class MySettings : SettingsProvider
    {
        private bool _isFirstRun;
        private string _hello;

        public MySettings() : base("MySettings.xml") { }

        [DefaultValue("What's up?")]
        public string HelloWorld
        {
            get { return _hello; }
            set
            {
                _hello = value;
                NotifyPropertyChanged("HelloWorld");
            }
        }

        [DefaultValue(true)]
        public bool IsFirstRun
        {
            get { return _isFirstRun; }
            set
            {
                bool old = _isFirstRun;
                _isFirstRun = value;
                if (value != old)
                {
                    NotifyPropertyChanged("IsFirstRun");
                }
            }
        }
    }
}</pre>
</div>
<p>Looking closer, inside the MySettings file:</p>
<ul>
<li>MySettings type derives from SettingsProvider, part of the helper code downloaded above.</li>
<li>The constructor calls the base class’s constructor with the name of a settings file to use within the isolated storage area for the phone application</li>
<li>Properties have backing fields and fire change notifications</li>
<li>Default values</li>
</ul>
<h3>Add the settings object to your App.xaml</h3>
<p>Now, open up App.xaml. Add an XMLNS prefix declaration for your project. I named my app project “Sample”, so it’s short:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:acd9bf42-6d28-4915-bf66-d21d8e7c8936" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">xmlns:local="clr-namespace:Sample"</pre>
</div>
<p>And then add your settings object to the resources (I’m omitting all the theme resources in App.xaml to make it clear where this goes only).</p>
<p><strong>AlwaysSaveOnChange</strong> needs to be set to true for Windows Phone applications: if you’re building a regular Silverlight app, the Application.Exit event works well and can be used to store. But on the phone, since an app may be in a paused or unknown state, this property tells my helper code to save the settings <em>whenever</em> a binding has a change notification. For performance impact should be minimal.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:13458972-7b46-4eb1-bc09-09a5287a27df" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;Application.Resources&gt;
        &lt;!-- Settings --&gt;
        &lt;local:MySettings x:Key="MySettings" AlwaysSaveOnChange="True" /&gt;
&lt;/Application.Resources&gt;</pre>
</div>
<h3>A simple TextBox binding</h3>
<p>Now on my MainPage.xaml, I am just going to bind to the Hello World property from the MySettings type. Any time you type characters into the text box, they will be saved, and always there when you run the app. No need to write code to save or read settings.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:30433b15-c4bf-475a-8a49-59b91a731f58" class="wlWriterEditableSmartContent">
<pre class="xml" name="code">&lt;TextBox
    Text="{Binding Source={StaticResource MySettings}, Path=HelloWorld, Mode=TwoWay}" /&gt;
</pre>
</div>
<h3>Good to go</h3>
<p>To pull it in, I’m going to add a page called FirstRun.xaml to the project. This will be the content that I want first-time users to see. Then, I need to add the code to call this from main page at startup:</p>
<p>I define a loaded event for this that checks whether the current instance has run the page yet (hacky, and not a permanent setting), and then checks whether the user wants to see the screen (which defaults to true in my settings file):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:3ec0659d-8aee-41bc-b130-2bd8f24eca37" class="wlWriterEditableSmartContent">
<pre class="csharp" name="code">if (!((App)App.Current).HasFirstRunCheckHappenedYet)
{
    ((App)App.Current).HasFirstRunCheckHappenedYet = true;

    MySettings settings = (MySettings)App.Current.Resources["MySettings"];
    if (settings != null &#038;&#038; settings.IsFirstRun)
    {
        NavigationService.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
    }
}</pre>
</div>
<p>It then uses the navigation service to navigate, if needed.</p>
<p>If you’d like to learn more about Silverlight data binding, do check out this MSDN resource: <a title="http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx" href="http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx">http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx</a></p>
<p>Some people have experimented with directly binding to the isolated storage settings file, but this approach gives your some separation – by having your own class, you can provide default values, even upgrade logic, and do some neat work.</p>
<p>This is based on a classic WPF post by <a href="http://blogs.msdn.com/patrickdanino/archive/2008/07/23/user-settings-in-wpf.aspx">Patrick Danino</a> which used the full .NET configuration classes. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/data-binding-user-settings-in-windows-phone-applications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>No March 2010 release of the Silverlight Toolkit</title>
		<link>http://www.jeff.wilcox.name/2010/03/no-march-release/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/no-march-release/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 00:08:04 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Silverlight Toolkit]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/no-march-release/</guid>
		<description><![CDATA[I’ve received a number of emails and questions from developers about the next release of the Silverlight Toolkit and wanted to take a moment to address the lack of a March release. Although we had previously talked about a March 2010 release to coincide with the Silverlight 4 RC at MIX, we have decided not [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve received a number of emails and questions from developers about the next release of the Silverlight Toolkit and wanted to take a moment to address the lack of a March release.
<p>Although we had previously talked about a March 2010 release to coincide with the Silverlight 4 RC at MIX, we have decided not to ship an interim release for the RC, since the final release of Silverlight 4 is coming next month.</p>
<p>This is a good thing for developers, the time we save by not releasing goes toward a better release overall when Silverlight 4 is final.</p>
<p>In the meantime, the release of the toolkit in November, for Silverlight 3, still works great on Silverlight 4 RC.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/no-march-release/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Silverlight Toolkit and the Windows Phone: WrapPanel, and a few others</title>
		<link>http://www.jeff.wilcox.name/2010/03/toolkit-and-the-windows-phone/</link>
		<comments>http://www.jeff.wilcox.name/2010/03/toolkit-and-the-windows-phone/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 20:27:34 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Silverlight Toolkit]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2010/03/toolkit-and-the-windows-phone/</guid>
		<description><![CDATA[Are you looking for WrapPanel for your Windows Phone application? Look no further. The Silverlight Toolkit has several controls that work pretty well on the Windows Phone. I wanted to provide my own informal look at how it’s working with Silverlight for Windows Phone today. Note that this information is only current as of today, [...]]]></description>
			<content:encoded><![CDATA[<p>Are you looking for WrapPanel for your Windows Phone application? Look no further. The Silverlight Toolkit has several controls that work pretty well on the Windows Phone.</p>
<p><a href="http://silverlight.codeplex.com/"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="WrapPanel" border="0" alt="WrapPanel" src="http://www.jeff.wilcox.name/wp-content/uploads/2010/03/WrapPanel.png" width="454" height="338" /></a> </p>
<p>I wanted to provide my own informal look at how it’s working with Silverlight for Windows Phone today.</p>
<p>Note that this information is only current as of today, 3/21, when used with the MIX-related CTP of the tools and emulator, and the November 2009 Silverlight Toolkit. A lot could change, and this is <strong>not exhaustive</strong>.</p>
<p>I’m also including some controls that are found in the Silverlight SDK today. I present these in order of how much I have used the components while building apps.</p>
<h3>WrapPanel and DockPanel</h3>
<p>Found in the Silverlight Toolkit, System.Windows.Controls.Toolkit.dll (SWC.Toolkit).</p>
<p>Work great.</p>
<p>If you just need the WrapPanel, and don’t want to include the entire toolkit assembly, you can just paste these source files into your application project instead (license: <a href="http://opensource.org/licenses/ms-pl.html">Ms-PL</a>):</p>
<ul>
<li><a href="http://silverlight.codeplex.com/sourcecontrol/network/Show?projectName=Silverlight&amp;changeSetId=35261#636618">OrientedSize.cs</a></li>
<li><a href="http://silverlight.codeplex.com/sourcecontrol/network/Show?projectName=Silverlight&amp;changeSetId=35261#638862">WrapPanel.cs</a></li>
</ul>
<h3>Charting and Data Visualization</h3>
<p>There is a known issue with LINQ that prevents the controls today from working perfectly. A small, targeted fix has been made in the charting codebase and a future release will work well on the device.</p>
<p>Re-templating and styling the control is very important, and required, for working on the phone in an acceptable manner. I hope to share any decent templates I can come up with.</p>
<h3>HeaderedItemsControl, HeaderedContentControl</h3>
<p>Work great. Split between System.Windows.Controls (SWC) and SWC.Toolkit.</p>
<h3>TreeView</h3>
<p>SWC. Functional; requires massive re-templating and styling. Font sizes are much too small, and the theme and visuals do not appear code-name “Metro” compatible.</p>
<h3>AutoCompleteBox</h3>
<p>Found in the System.Windows.Controls.Input SDK library of the Silverlight 3 SDK.</p>
<p>Works OK, not ready for general development use.</p>
<p>Drop-down appears well. Major features all work. However, touching an entry in the drop down only performs selection. A second touch is required to verify the choice, effectively requiring a double-tap in use.</p>
<h3>Calendar, DatePicker</h3>
<p>SWC. Limited functionality, too small visually. Not designed for touch – not enough space to reliably click on a date. Require massive re-templating. Do not resemble the same experience as the date picker built into the Windows Phone operating system.</p>
<h3>GridSplitter</h3>
<p>Works, but may pose difficult to use on a device: requires much larger padding and custom templates to make the touch area visible and useful.</p>
<h3>Not yet checked</h3>
<p>DataGrid, DataPager, ChildWindow, Label, NumericUpDown, DomainUpDown, DataForm, Rating, TimePicker, TimeUpDown, GlobalCalendar, TransitioningContentControl, TreeMap, BusyIndicator, Viewbox, Expander, Accordion, drag and drop features, and many more.</p>
<p>We’re also still developing a story for the toolkit’s phone story moving forward. As there is a lot of momentum around the phone in the company, it’s very likely that some set of phone tools, samples, and toolkits come out.</p>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2010/03/toolkit-and-the-windows-phone/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
