<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Kiener&#039;s Blog</title>
	<atom:link href="http://blog.thekieners.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thekieners.com</link>
	<description>Blog of Beat Kiener, containing my experiences, thoughts, comments and questions</description>
	<lastBuildDate>Wed, 10 Mar 2010 08:50:59 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='blog.thekieners.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/ce07d63ce72ea1c22a336770b583f24a?s=96&#038;d=http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kiener&#039;s Blog</title>
		<link>http://blog.thekieners.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.thekieners.com/osd.xml" title="Kiener&#039;s Blog" />
	<atom:link rel='hub' href='http://blog.thekieners.com/?pushpress=hub'/>
		<item>
		<title>MCTS Exam .NET Framework Application Development</title>
		<link>http://blog.thekieners.com/2010/03/10/mcts-exam-net-framework-application-development/</link>
		<comments>http://blog.thekieners.com/2010/03/10/mcts-exam-net-framework-application-development/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 08:50:59 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[MCTS]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/03/10/mcts-exam-net-framework-application-development/</guid>
		<description><![CDATA[Today I have passed my second Microsoft Certification Exam 70-536 &#34;Microsoft .NET Application Development&#34; successfully. After working about 6 year with the .NET technology it was quite an easy tasks to pass this exam. 

       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=408&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Today I have passed my second Microsoft Certification Exam 70-536 &quot;Microsoft .NET Application Development&quot; successfully. After working about 6 year with the .NET technology it was quite an easy tasks to pass this exam. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/03/image4.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/03/image_thumb3.png?w=709&#038;h=542" width="709" height="542" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/408/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=408&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/03/10/mcts-exam-net-framework-application-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/03/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Deep Zoom Collection Downloader</title>
		<link>http://blog.thekieners.com/2010/03/02/deep-zoom-collection-downloader/</link>
		<comments>http://blog.thekieners.com/2010/03/02/deep-zoom-collection-downloader/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 05:51:04 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Deep Zoom]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/03/02/deep-zoom-collection-downloader/</guid>
		<description><![CDATA[Just for fun I’ve implemented a Deep Zoom Tiles Downloader which recreates the original image from a deep zoom composition. Additionally the downloader can download the original composition from the website to your local disk. The downloader follows the principals of a pure MVVM application.
No, i have not too much time. I’m pretty well experienced [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=404&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Just for fun I’ve implemented a <i>Deep Zoom Tiles Downloader</i> which recreates the original image from a deep zoom composition. Additionally the downloader can download the original composition from the website to your local disk. The downloader follows the principals of a pure MVVM application.</p>
<p>No, i have not too much time. I’m pretty well experienced with the MVVM pattern in Silverlight but not in the WPF runtime. To get more familiar with MVVM in WPF and to see the difference in a practical manner I decided to put the implementation into a ViewModel and to build a WPF-View on top of them.</p>
<h2>The Application</h2>
<p>In the <em>Image Rebuilder</em> tab, the application allows to set the deep zoom image settings or discover them automatically from a standard Deep Zoom Composer xml-file.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/03/image.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/03/image_thumb.png?w=684&#038;h=511" width="684" height="511" /></a> </p>
<p>The downloader allows you to set each deep zoom composition parameter manually, because there are deep zoom compositions out there in the internet without having the standard Deep Zoom Composer XML format. </p>
<p>One nice example of such a collection is the <a href="http://rubrik.ch.msn.com/reportagen/zermatt.aspx" target="_blank">“Matterhorn Deep Zoom Collection”</a> created by Ronnie Saurenmann (Microsoft Switzerland).</p>
<p><a href="http://rubrik.ch.msn.com/reportagen/zermatt.aspx" target="_blank"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/03/image1.png?w=90&#038;h=72" width="90" height="72" /></a> </p>
<p>Enter the following values to test the downloader with his collection:</p>
<ul>
<li>URL Pattern: http://ronnie.blob.core.windows.net/zermatt/Tiles/560mmMatterhornSchwarzsee/{0}/{1}_{2}.jpg</li>
<li>Levels: 17</li>
<li>Tile Width: 254</li>
<li>Tile Height: 254</li>
<li>Tile Overlap: 1</li>
<li>Image Width: 55569</li>
<li>Image Height: 30064</li>
</ul>
<p>&#160;</p>
</p>
<p>In the <em>Tiles Downloader</em> tab, the application allows to set the root folder of the deep zoom composition (containing the folder levels 0, 1, 2, 3, 4, 5, etc), specifying the download target folder and to start the download.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/03/image2.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/03/image_thumb1.png?w=665&#038;h=497" width="665" height="497" /></a> </p>
<h2>&#160;</h2>
<h2>ViewModel implementation</h2>
<p>I’m using the Bitmap from the GDI to rebuild the image. A 32 bit RGB formatted bitmap uses 32 bit i.e. 4 bytes to store data for each pixel. So if you try to rebuild a large deep zoom composition with as example of 50000&#215;50000 pixels then the memory the downloader needs to allocate dynamically for the image is very large 50000*50000*4 bytes which is roughly about 9 GB in memory. While this is not possible with GDI the downloader downloads the image in smaller portion so you might get an image portioned as following (example show image in 5 portions):</p>
<p><a href="http://bkiener.files.wordpress.com/2010/03/image3.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/03/image_thumb2.png?w=593&#038;h=438" width="593" height="438" /></a> </p>
<p>It should be very easy to build the final image with Photoshop or ImageMagick from the portioned tiles. Feel free to extend the downloader with a better approach while using a 3<sup>rd</sup> party image lib.</p>
<p>A note about the performance: the downloader rebuilds or downloads images tile-by-tile. I did not have enough time to do it parallel in several threads.</p>
<h2>Summary</h2>
<p>It’s quite the same to implement a ViewModel in WPF and Silverlight for such very small applications. The only difference I can see so far is the missing constraint for asynchron web request in WPF. This makes the implementation a little bit simpler. The binding expressions are identically to Silverlight, because I don’t need any special here. The command binding was easier to write because the Command property is supported from the ButtonBase natively (Silverlight will provide the same in version 4).</p>
<p>I know, this is a quite simple application and things get complicated when the application gets more complex.</p>
<p>Feedbacks are welcome.</p>
<h2>Source code</h2>
<p>You can download the source code here:</p>
<p><a href="http://files.thekieners.com/blogcontent/2010/DeepZoomDownloader/source.zip" target="_blank">http://files.thekieners.com/blogcontent/2010/DeepZoomDownloader/source.zip</a></p>
<h2>One final note</h2>
<p>This downloader was implemented just for fun. Please consider copyrights when downloading deep zoom images.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/404/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/404/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/404/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/404/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/404/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/404/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/404/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/404/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/404/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/404/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=404&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/03/02/deep-zoom-collection-downloader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/03/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/03/image1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/03/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/03/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>The Future of Business Applications</title>
		<link>http://blog.thekieners.com/2010/02/24/the-future-of-business-applications/</link>
		<comments>http://blog.thekieners.com/2010/02/24/the-future-of-business-applications/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 07:13:46 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[RIA]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/24/the-future-of-business-applications/</guid>
		<description><![CDATA[Today the Netzwoche magazine has published a Silverlight/RIA story in cooperation with Microsoft Switzerland. The title of the story is “The Future of Business Applications”. The story contains an interview which I was allowed to give (in German only).
NW10_04_Dossier_Microsoft.pdf

       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=391&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Today the <a href="http://www.netzwoche.ch" target="_blank">Netzwoche</a> magazine has published a Silverlight/RIA story in cooperation with Microsoft Switzerland. The title of the story is “<em>The Future of Business Applications”</em>. The story contains an interview which I was allowed to give (in German only).</p>
<p><a title="http://files.thekieners.com/blogcontent/2010/NW10_04_Dossier_Microsoft.pdf" href="http://files.thekieners.com/blogcontent/2010/NW10_04_Dossier_Microsoft.pdf" target="_blank">NW10_04_Dossier_Microsoft.pdf</a></p>
<p><a href="http://files.thekieners.com/blogcontent/2010/NW10_04_Dossier_Microsoft.pdf" target="_blank"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/02/image4.png?w=463&#038;h=609" width="463" height="609" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/391/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/391/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/391/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/391/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/391/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/391/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/391/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/391/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/391/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/391/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=391&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/24/the-future-of-business-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/image4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>How to make Visifire Chart bindable to ViewModel</title>
		<link>http://blog.thekieners.com/2010/02/22/how-to-make-visifire-chart-bindable-to-viewmodel/</link>
		<comments>http://blog.thekieners.com/2010/02/22/how-to-make-visifire-chart-bindable-to-viewmodel/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 11:05:08 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Chart]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Visifire]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/22/how-to-make-visifire-chart-bindable-to-viewmodel/</guid>
		<description><![CDATA[The Visifire chart control is very cool and handy, but there is one missing part: it does not support data binding. The Visifire team confirmed that the current release (version 3.0.1.0) is not bindable and they are working on this issue with high priority: (http://www.visifire.com/forums/index.php?showtopic=1631).     Currently I’m working in a large [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=388&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.visifire.com/">Visifire chart control</a> is very cool and handy, but there is one missing part: it does not support data binding. The Visifire team confirmed that the current release (version 3.0.1.0) is not bindable and they are working on this issue with high priority: (<a href="http://www.visifire.com/forums/index.php?showtopic=1631" target="_blank">http://www.visifire.com/forums/index.php?showtopic=1631</a>).     <br />Currently I’m working in a large Silverlight project where we use the Visifire chart and doing straight MVVM.</p>
<h2><b>First attempt</b></h2>
<p>In my first attempt I created a BindableDataSeries class inherited from DataSeries like the same concept I did to make the Silverlight Toolkit charts mulit-series bindable. See here: <a href="/2010/02/07/databinding-multi-series-charts" target="_blank">http://blog.thekieners.com/2010/02/07/databinding-multi-series-charts</a></p>
<p>I added a DataPointSource of type IEnumarable and DataPointTemplate of type DataTemplate to the BindableDataSeries class. Both properties are bindable. When the SeriesSource is set then DataSeries elements are generated based on the data template in the SeriesTemplate property in the same manner as an ItemsControl generates its items. Finally the generated DataSeries are added to the Series collection.</p>
<p>Now I’m able to bind the data point to my ViewModel as following:</p>
<pre>    &lt;vc:Chart&gt;
        &lt;vc:Chart.Series&gt;
            &lt;local:BindableDataSeries DataPointSource=&quot;<span style="color:#8b0000;">{Binding SalesData}</span>&quot; &gt;
                &lt;local:VisifireBindableDataSeries.DataPointTemplate&gt;
                    &lt;DataTemplate&gt;
                        &lt;vc:DataPoint AxisXLabel=&quot;<span style="color:#8b0000;">{Binding SalesName}</span>&quot;
                                      YValue=&quot;<span style="color:#8b0000;">{Binding SalesPerformance}</span>&quot;/&gt;
                    &lt;/DataTemplate&gt;
                &lt;/local:VisifireBindableDataSeries.DataPointTemplate&gt;
            &lt;/local:BindableDataSeries&gt;
        &lt;/vc:Chart.Series&gt;
    &lt;/vc:Chart&gt;</pre>
<p>Unfortunately there is still one problem. The DataPoint is an UIElement which is never part of the visual tree and binding gets not applied, because the binding is not executed when the element is not in the visual tree. As a result the DataPoint properties remain empty.</p>
<h2>Second attempt</h2>
<p>It shows to me that the only way to setup a Visifire Chart with data from a ViewModel is by writing code. How to do this without getting a strong reference between the View and the ViewModel? Remember to MVVM concepts, when creating a strong reference between View and ViewModel (either in one or both ways) you will lose many advantages the MVVM serves you.</p>
<p>In my second attempt I’ve created a Visifire Chart Wrapper which contains the most common properties of the Visifire Chart as bondable dependency properties.</p>
<p>Let me explain it step by step.</p>
<p>The control is inherited from System.Windows.Control and not from ContentControl, because there is no need for a composite control. The VisifireWrapper uses a static template originated from the code and not from the generic.xaml, because I don’t want to allow to re-template it. In the OnApplyTemplate override is a check implemented to guarantee this. Microsoft uses the same concept in the ViewBox control contained in the Silverlight Toolkit (<a href="https://silverlight.svn.codeplex.com/svn/Release/Silverlight3/Source/Controls.Toolkit/Viewbox/Viewbox.cs" target="_blank">https://silverlight.svn.codeplex.com/svn/Release/Silverlight3/Source/Controls.Toolkit/Viewbox/Viewbox.cs</a>).</p>
<pre>    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// VisifireWrapper serves as an Visifre Chart Wrapper to get the Chart MVVM bindable.</span>
    <span style="color:#808080;">/// You must inherit from this class an implement OnUpdateChart method.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">abstract</span> <span style="color:#0000ff;">class</span> VisifireWrapper : Control
    {

        <span style="color:#0000ff;">public</span> VisifireWrapper()
        {
          <span style="color:#008000;">// Load the default template</span>
          <span style="color:#0000ff;">this</span>.Template = DefaultTemplate = XamlReader.Load(DefaultTemplateMarkup) <span style="color:#0000ff;">as</span> ControlTemplate;
          ApplyTemplate();
        }

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// XAML markup used to define the write-once wrapper template.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">const</span> <span style="color:#0000ff;">string</span> DefaultTemplateMarkup =
            &quot;<span style="color:#8b0000;">&lt;ControlTemplate </span>&quot; +
            &quot;<span style="color:#8b0000;">    xmlns='http://schemas.microsoft.com/client/2007'  </span>&quot; +
            &quot;<span style="color:#8b0000;">    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'  </span>&quot; +
            &quot;<span style="color:#8b0000;">    xmlns:local='clr-namespace:VisifireMvvmIntegrationDemo;assembly=VisifireMvvmIntegrationDemo' </span>&quot; +
            &quot;<span style="color:#8b0000;">    TargetType='local:VisifireWrapper' &gt; </span>&quot; +
            &quot;<span style="color:#8b0000;">    &lt;ContentPresenter  </span>&quot; +
            &quot;<span style="color:#8b0000;">        Content='{TemplateBinding Chart}'  </span>&quot; +
            &quot;<span style="color:#8b0000;">        HorizontalAlignment='Stretch'  </span>&quot; +
            &quot;<span style="color:#8b0000;">        VerticalAlignment='Stretch'  /&gt; </span>&quot; +
            &quot;<span style="color:#8b0000;">&lt;/ControlTemplate&gt; </span>&quot;;

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Gets or sets the default ControlTemplate of the VisifireWrapper.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> ControlTemplate DefaultTemplate { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }

        <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">sealed</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnApplyTemplate()
        {
            <span style="color:#0000ff;">base</span>.OnApplyTemplate();

            <span style="color:#008000;">// Ensure the Template property never changes from the</span>
            <span style="color:#008000;">// DefaultTemplate, and only apply it one time.</span>
            <span style="color:#0000ff;">if</span> (Template != DefaultTemplate)
                <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> InvalidOperationException(&quot;<span style="color:#8b0000;">The template can only be applied one time.</span>&quot;);
        }
    }</pre>
<p>&#160;</p>
<p>The template contains a ContentPresenter which is data bound to the Chart property. The Chart property is set in the OnUpdateChart method which I’m going to introduce in a minute.</p>
<p>As next I added the most commonly used Visifire properties as dependency properties. Please find the full source code of the beneath dependency properties in the attached source.</p>
<pre><span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Gets or sets a collection used to generate the data point series.</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> IEnumerable ChartSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(ChartSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(ChartSourceProperty, <span style="color:#0000ff;">value</span>); }
}

<span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Gets or sets a collection used to generate the chart multiline-title.</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> IEnumerable TitlesSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(TitlesSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(TitlesSourceProperty, <span style="color:#0000ff;">value</span>); }
}

<span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Gets or sets a collection used to generate X-Axes</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> IEnumerable AxesXSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(AxesXSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(AxesXSourceProperty, <span style="color:#0000ff;">value</span>); }
}

<span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Gets or sets a collection used to generate Y-Axes</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> IEnumerable AxesYSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(AxesYSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(AxesYSourceProperty, <span style="color:#0000ff;">value</span>); }
} </pre>
<p><em></em></p>
<p><em>ChartSource</em> will point to a collection of chart points or a collection of multi chart data. Multi chart data is meant to be used when you want to defined the numbers of lines in a line-chart dynamically. The attached demo project contains an example of this.</p>
<p><em>TitlesSource</em> points to a collection of title information. Visifire Charts allow you to define a title with multiple lines. Each item in the collection is meant to be one line in the chart title.</p>
<p><em>AxesXSource</em> and <em>AxesYSource</em> points to collections of specific axes-captions or axes-settings.</p>
<p>The VisifireWrapper contains abstract method <em>OnUpdateChart</em>. When overridden in sub class it updates the Visifire Chart wrapped by the VisifireWrapper control. The method is called in the first layout pass after one of the sources <em>ChartSource</em>, <em>TitlesSource</em>, <em>AxesXSource</em> or <em>AxesYSource</em> has changed. This is unlike the ItemsControl where the child items gets generated when the source changes. Recently I discovered that the DataGrid works exactly the same way: it generates its items (rows, etc) in the first layout pass after the ItemsSource has changed. But why I do it that way? The answer is performance, as you can read in the next section.</p>
<p>The charts are very nice animated during the first load (this is quite import for us, because it is part of a bigger aim to serve a new user experience to our customers. But this is another story&#8230;). Unfortunately the Visifire Chart does not allow updating DataPoints in every circumstance. Changing existing DataPoints is not a problem until you want to add or remove DataPoints. When you add DataPoints to an existing series the chart does this animated but the output is not correct as you can see in the print screen below:</p>
<p>Before…</p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image001.png"><img style="display:inline;border-width:0;" title="clip_image001" border="0" alt="clip_image001" src="http://bkiener.files.wordpress.com/2010/02/clip_image001_thumb.png?w=331&#038;h=195" width="331" height="195" /></a></p>
<p>…and after adding one DataPoint</p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image002.png"><img style="display:inline;border-width:0;" title="clip_image002" border="0" alt="clip_image002" src="http://bkiener.files.wordpress.com/2010/02/clip_image002_thumb.png?w=331&#038;h=197" width="331" height="197" /></a></p>
<p>Adding or removing DataPoints is not possible so far (version 3.0.1.0). The solution is to remove all DataPoints and re-add it to the chart. In that way we lose the animation, because the chart does animate only on first time load or when updating existing points. Therefore our solution is quite simple: every time any of the chart sources changes a new chart control instance is created with new DataPoints. OnUpdateChart override looks like this:</p>
<pre><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> ColumnChart : VisifireWrapper
{
    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnUpdateChart()
    {

        <span style="color:#008000;">// init chart control</span>
        Chart chart = <span style="color:#0000ff;">new</span> Chart();
        chart.Theme = &quot;<span style="color:#8b0000;">Theme2</span>&quot;;
        chart.AnimatedUpdate = <span style="color:#0000ff;">true</span>;
        chart.AnimationEnabled = <span style="color:#0000ff;">true</span>;
        chart.View3D = <span style="color:#0000ff;">true</span>;

        <span style="color:#008000;">// create data series when DataSource is set</span>
        <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.ChartSource != <span style="color:#0000ff;">null</span>)
        {
            <span style="color:#008000;">// init data point series</span>
            DataSeries series = <span style="color:#0000ff;">new</span> DataSeries();
            series.RenderAs = RenderAs.Column;
            series.ShadowEnabled = <span style="color:#0000ff;">true</span>;
            series.XValueType = ChartValueTypes.Date;
            series.YValueFormatString = &quot;<span style="color:#8b0000;">hh:mm tt</span>&quot;;
            series.SelectionEnabled = <span style="color:#0000ff;">false</span>;
            chart.Series.Add(series);

            <span style="color:#0000ff;">foreach</span> (PointData item <span style="color:#0000ff;">in</span> <span style="color:#0000ff;">this</span>.ChartSource)
            {
                DataPoint dataPoint = <span style="color:#0000ff;">new</span> DataPoint();
                dataPoint.XValue = item.Date;
                dataPoint.YValue = item.Value;
                series.DataPoints.Add(dataPoint);
            }
        }

        <span style="color:#008000;">// set the chart title</span>
        <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.TitlesSource != <span style="color:#0000ff;">null</span>)
        {
            <span style="color:#0000ff;">foreach</span> (<span style="color:#0000ff;">string</span> title <span style="color:#0000ff;">in</span> <span style="color:#0000ff;">this</span>.TitlesSource)
            {
                Title chartTitle = <span style="color:#0000ff;">new</span> Title();
                chartTitle.Text = title;
                chart.Titles.Add(chartTitle);
            }
        }

        <span style="color:#008000;">// completely replace the chart control</span>
        <span style="color:#0000ff;">this</span>.Chart = chart;

    }

}</pre>
</p>
<p><font face="Courier New"></font></p>
<p>To set the values for your needs, the <a href="http://www.visifire.com/silverlight_charts_gallery.php" target="_blank">Visifire Chart samples</a> provide excellent demos as XAML and its very simple to translate it into imperative code. </p>
<p>At the end of the method you must set the Chart property with the new chart. The new chart gets data bound to the ContentPresenter through TemplateBinding.</p>
<h2>Internals</h2>
<p>Let’s have a look into the internals of the abstract class <em>VisifireWrapper</em>.</p>
<p>Below is the implementation of the <em>ChartSource</em> dependency property, served as a model for the other properties:</p>
<pre><span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Gets or sets a collection used to generate the data point series.</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> IEnumerable ChartSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(ChartSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(ChartSourceProperty, <span style="color:#0000ff;">value</span>); }
}
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">readonly</span> DependencyProperty ChartSourceProperty =
    DependencyProperty.Register(&quot;<span style="color:#8b0000;">ChartSource</span>&quot;,
        <span style="color:#0000ff;">typeof</span>(IEnumerable),
        <span style="color:#0000ff;">typeof</span>(VisifireWrapper),
        <span style="color:#0000ff;">new</span> PropertyMetadata(<span style="color:#0000ff;">new</span> PropertyChangedCallback(OnChartSourceChanged)));

<span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> OnChartSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    IEnumerable oldValue = (IEnumerable)e.OldValue;
    IEnumerable newValue = (IEnumerable)e.NewValue;
    VisifireWrapper source = (VisifireWrapper)d;
    source.OnChartSourceChanged(oldValue, newValue);
}

<span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnChartSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    _chartSourceCollectionChanged.SetEventSource(newValue);

    InvalidateChart();
}</pre>
<p>&#160;</p>
<p>In the changed handler are two things to do:</p>
<ul>
<li>Set the event source for the WeakEventSource wrapper. The wrapper serves a weak event pattern to listen for CollectionChanged event in a non-memory-leaking way. In two previous post I explain in detail what the <a href="~/2010/02/17/weakeventsource-implementation-2/" target="_blank">WeakEventSource</a> and <a href="/2010/02/11/simple-weak-event-listener-for-silverlight/" target="_blank">WeakEventListener</a> serves you. </li>
<li>Secondly set an internal flag to invalidate the chart so it gets updated the next time the control renders its child. </li>
</ul>
<p>You can easily implement additional dependency properties. When using the WeakEventSource you do not have to think about possible memory leaks when listen for source-events.</p>
<h2>Summary</h2>
<p>The VisifireWrapper is a very helpful base class to implement custom Visifire charts which are bindable to a ViewModel without having a strong reference between the View and ViewModel. The control supports the Silverlight content model except data-templating and encapsulates the weak-event-pattern. In addition the implementation shows the usage of the WeakEventSource implementation I did from a previous post.</p>
<p>Any feedbacks are welcome.</p>
<h2>Demo &amp; Source</h2>
<p>Below you can find a <a href="http://files.thekieners.com/blogcontent/2010/VisifireWrapper/" target="_blank">demo project</a> and the full <a href="http://files.thekieners.com/blogcontent/2010/VisifireWrapper/Source.zip" target="_blank">source code</a> of the VisifireWrapper and WeakEventSource. The demo contains a Single-Series and Multi-Series chart and a demo implementation for common chart types.</p>
<p><a href="http://files.thekieners.com/blogcontent/2010/VisifireWrapper/" target="_blank"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image002" border="0" alt="clip_image002" src="http://bkiener.files.wordpress.com/2010/02/clip_image0022.jpg?w=705&#038;h=441" width="705" height="441" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/388/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/388/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/388/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/388/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/388/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/388/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/388/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/388/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/388/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/388/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=388&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/22/how-to-make-visifire-chart-bindable-to-viewmodel/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image001_thumb.png" medium="image">
			<media:title type="html">clip_image001</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image002_thumb.png" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image0022.jpg" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>
	</item>
		<item>
		<title>WeakEventSource implementation</title>
		<link>http://blog.thekieners.com/2010/02/17/weakeventsource-implementation-2/</link>
		<comments>http://blog.thekieners.com/2010/02/17/weakeventsource-implementation-2/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 19:06:29 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Pattern]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Weak Event]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/17/weakeventsource-implementation-2/</guid>
		<description><![CDATA[The Situation
Implementing custom controls with dependency properties binding to an IEnumarable object collection is not a developer’s daily task. Most of the time one would use the ItemsControl which already provides the ItemsSource property together with the ItemsTemplate property. But what when the functionality provided with the ItemsControl does not meet your requirement? Then you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=380&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<h2>The Situation</h2>
<p>Implementing custom controls with dependency properties binding to an IEnumarable object collection is not a developer’s daily task. Most of the time one would use the ItemsControl which already provides the ItemsSource property together with the ItemsTemplate property. But what when the functionality provided with the ItemsControl does not meet your requirement? Then you can implement your own dependency property for the source collection like the following:</p>
<pre>#region DataPointsSource (DependencyProperty)

<span style="color:#0000ff;">public</span> IEnumerable DataPointsSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(DataPointsSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(DataPointsSourceProperty, <span style="color:#0000ff;">value</span>); }
}
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">readonly</span> DependencyProperty DataPointsSourceProperty =
    DependencyProperty.Register(&quot;<span style="color:#8b0000;">DataPointsSource</span>&quot;,
                        <span style="color:#0000ff;">typeof</span>(IEnumerable),
                        <span style="color:#0000ff;">typeof</span>(CustomControl),
                        <span style="color:#0000ff;">new</span> PropertyMetadata(<span style="color:#0000ff;">new</span> PropertyChangedCallback(OnDataPointsSourceChanged)));

<span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> OnDataPointsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}  

#endregion</pre>
<p>&#160;</p>
<p>To fully support the Silverlight content model you should check whether the source collection implements INotifyCollectionChanged interface or not. If the source implements INotifyCollectionChanged the custom control code should response to this event and Add/Remove/Replace items accordingly. Attaching the necessary event as following can produce a serious memory leaking problem:</p>
<pre><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnDataPointsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    <span style="color:#008000;">// implements INotifyCollectionChanged?</span>
    var sourceCollectionChanged = newValue <span style="color:#0000ff;">as</span> INotifyCollectionChanged;
    <span style="color:#0000ff;">if</span> (sourceCollectionChanged != <span style="color:#0000ff;">null</span>)
    {
        <span style="color:#008000;">// attach the event</span>
        sourceCollectionChanged.CollectionChanged += OnCollectionChanged;
    }
}</pre>
<p>&#160;</p>
<p>In a <a href="http://blog.thekieners.com/2010/02/11/simple-weak-event-listener-for-silverlight/" target="_blank">previous post</a> I explained in detail why there can be a memory leak and how we prevent it in our SL controls. The solution is quite the same as Microsoft uses in the Silverlight Toolkit. Additionally <a href="http://blogs.msdn.com/delay/archive/2009/03/09/controls-are-like-diapers-you-don-t-want-a-leaky-one-implementing-the-weakevent-pattern-on-silverlight-with-the-weakeventlistener-class.aspx" target="_blank">David Anson wrote an excellent article</a> about leaking controls and the solution they use in the Silverlight Toolkit. </p>
<p>So, writing code using the WeakEventListener pattern described in the blog posts above it still a tedious task. First you have to detach the previous listener and secondly you have to create a new weak-listener for the new event source. This result in these lines of code:</p>
<pre><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnDataPointsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    <span style="color:#008000;">// detach previous event source</span>
    <span style="color:#0000ff;">if</span> (_weakEventListener != <span style="color:#0000ff;">null</span>)
    {
        <span style="color:#008000;">//  detach WeakEventListener</span>
        _weakEventListener.Detach();
        _weakEventListener = <span style="color:#0000ff;">null</span>;
    }

    <span style="color:#008000;">// attach new WeakEventListener when new source implements INotifyCollectionChanged</span>
    var sourceCollectionChanged = newValue <span style="color:#0000ff;">as</span> INotifyCollectionChanged;
    <span style="color:#0000ff;">if</span> ( sourceCollectionChanged != <span style="color:#0000ff;">null</span>)
    {
        <span style="color:#008000;">// create WeakEventListener. Pass Listener and EventSource instance to it.</span>
        var weakListener = <span style="color:#0000ff;">new</span> WeakEventListener&lt;VisifireMvvmWrapperDemo,
                                      INotifyCollectionChanged,
                                      NotifyCollectionChangedEventArgs&gt;(<span style="color:#0000ff;">this</span>, sourceCollectionChanged);
        <span style="color:#008000;">// register handler</span>
        sourceCollectionChanged.CollectionChanged += weakListener.OnEvent;
        <span style="color:#008000;">// define event handler to handle the event.</span>
        weakListener.OnEventAction = (instance, source, e) =&gt;
        {
            <span style="color:#008000;">// event handling code</span>
            instance.OnCollectionChanged(instance, e);
        };
        <span style="color:#008000;">// define action to detach the handler</span>
        weakListener.OnDetachAction = (listener, source) =&gt;
        {
            <span style="color:#008000;">// unregister handler</span>
            source.CollectionChanged -= listener.OnEvent;
        };
        <span style="color:#008000;">// ensure there is no reference from the listener to the weakListener</span>
        weakListener = <span style="color:#0000ff;">null</span>;
    }

}</pre>
<p>Due to the fact that we use this pattern quite often for custom control development, I was looking for a solution which is easier to use. </p>
<h2>Our solution</h2>
<p>With an additional wrapper encapsulating the WeakEventListener our developers can now write just the following lines of code to get the same result:</p>
<pre><span style="color:#0000ff;">private</span> CollectionChangedWeakEventSource _sourceChanged;

<span style="color:#0000ff;">public</span> CustomControl()
{
    <span style="color:#008000;">// setup wrapper for CollectionChanged</span>
    _sourceChanged = <span style="color:#0000ff;">new</span> CollectionChangedWeakEventSource();
    _sourceChanged.CollectionChanged += <span style="color:#0000ff;">new</span> NotifyCollectionChangedEventHandler(sourceChanged_CollectionChanged);
}

<span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnDataPointsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    <span style="color:#008000;">// just set the event source to the wrapper</span>
    _sourceChanged.SetEventSource(newValue);
}

<span style="color:#0000ff;">void</span> sourceChanged_CollectionChanged(<span style="color:#0000ff;">object</span> sender, NotifyCollectionChangedEventArgs e)
{

}</pre>
<pre>&#160;</pre>
<p>In the control constructor (or when I use the wrapper the first time) I set up an instance of the CollectionChangedWeakEventSource and attach the CollectionChanged event. In the OnDataPointsSourceChanged handler I just set the source object for the wrapper. A previous source collection (oldValue) gets detached from the wrapper automatically when you call SetEventSource with the new value. The object passed to the method SetEventSource gets attached when the object implements INotifyCollectionChanged. </p>
<p>The class CollectionChangedWeakEventSource is quite easy to understand. It wraps just one event and uses the WeakEventListener class for the weak event pattern.</p>
<pre><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> CollectionChangedWeakEventSource : WeakEventSourceBase&lt;INotifyCollectionChanged&gt;
{
  <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> WeakEventListenerBase CreateWeakEventListener(INotifyCollectionChanged eventObject)
  {
<span style="color:#008000;">        // create a WeakEventListener</span></pre>
<pre>        var weakListener = <span style="color:#0000ff;">new</span> WeakEventListener&lt;CollectionChangedWeakEventSource,
                                                 INotifyCollectionChanged,
                                                 NotifyCollectionChangedEventArgs&gt;(<span style="color:#0000ff;">this</span>, eventObject);
        weakListener.OnDetachAction = (listener, source) =&gt;
        {
            source.CollectionChanged -= listener.OnEvent;
        };
        weakListener.OnEventAction = (instance, source, e) =&gt;
        {
            <span style="color:#008000;">// fire event</span>
            <span style="color:#0000ff;">if</span> (instance.CollectionChanged != <span style="color:#0000ff;">null</span>)
                instance.CollectionChanged(source, e);
        };
        eventObject.CollectionChanged += weakListener.OnEvent;

        <span style="color:#0000ff;">return</span> weakListener;
  }

  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">event</span> NotifyCollectionChangedEventHandler CollectionChanged;

}</pre>
<pre>&#160;</pre>
<p>The base class WeakEventSourceBase contains the general code to make the custom wrapper as simple as possible. As a result it is quite easy to implement an event wrapper for another event like the PropertyChanged event. Additionally I wrote a <a href="http://files.thekieners.com/blogcontent/WeakEventSource.txt" target="_blank">code snippet which is available here</a>. </p>
<p>At the end of this post you can find the source code of WeakEventSourceBase. </p>
<p>Some explanation to the code: </p>
<ul>
<li>WeakEventSourceBase contains a check to verify whether the implementation is correct or not. This check is executed only if a debugger is attached. Please note: I don’t use the Conditional(“DEBUG”) attribute to enable/disable this check, because we put the WeakEventSourceBase class into a common framework lib and this lib is RELEASE compiled. </li>
<li>Calling SetEventSource(null) is the same as calling Detach() </li>
<li>When setting a new event source, the previous source gets detached </li>
<li>When setting an event source which does not implement the event, it does not get attached, but the EventSource property is set to this instance and an previous event source gets detached. </li>
<li>The class WeakEventListenerBase is new due to the refactoring that was needed to get a non-generic declaration for the CreateWeakEventListener method return value. </li>
</ul>
<h2>Summary</h2>
<p>The WeakEventSource implementation is a weak-event-pattern implementation based on the WeakEventListener. The class helps us to reduce writing tedious code in custom control development, reduces memory leaks which are hard to find and last but not least it is easier to review custom control written that way, because a Reviewer must not have full knowledge about the weak-event pattern. </p>
<p>In a blog post later this week I’m going to demonstrate a complete custom control implementation using this WeakEventSource implementation. </p>
<p>&#160;</p>
<h2>Source Code</h2>
<p><a href="http://files.thekieners.com/blogcontent/WeakEventSourceDemo.zip" target="_blank">Here you can find the full source code.</a></p>
<p><a href="http://files.thekieners.com/blogcontent/WeakEventSourceDemo.zip" target="_blank"><img title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/02/image2.png?w=68&amp;h=68&#038;h=68" width="68" height="68" /></a></p>
<p>WeakEventSourceBase class:</p>
<pre><span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#808080;">/// Base class to wrap a specific event with the WeakEventListener.</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#808080;">/// &lt;typeparam name=&quot;TSource&quot;&gt;The type of the event source.&lt;/typeparam&gt;</span>
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">abstract</span> <span style="color:#0000ff;">class</span> WeakEventSourceBase&lt;TSource&gt;
     where TSource : <span style="color:#0000ff;">class</span>
{

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// A weak reference to the event source</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#0000ff;">private</span> WeakReference _weakEventSource;

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">///  A weak reference to the WeakEventListener instance.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#0000ff;">private</span> WeakReference _weakListener;

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// Gets the event source instance which this listener is using.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#808080;">/// &lt;remarks&gt;</span>
    <span style="color:#808080;">/// The reference to the event source is weak.</span>
    <span style="color:#808080;">/// &lt;/remarks&gt;</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">object</span> EventSource
    {
        <span style="color:#0000ff;">get</span>
        {
            <span style="color:#0000ff;">if</span> (_weakEventSource == <span style="color:#0000ff;">null</span>)
                <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;

            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>._weakEventSource.Target;
        }
    }

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// Set the event source for this instance. </span>
    <span style="color:#808080;">/// When passing a new event source it replaces the event source the </span>
    <span style="color:#808080;">/// listener is listen for an event. When passing null/nothing is detaches </span>
    <span style="color:#808080;">/// the previous event source from this event listener. </span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#808080;">/// &lt;param name=&quot;eventSource&quot;&gt;The event source instance.&lt;/param&gt;</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> SetEventSource(<span style="color:#0000ff;">object</span> eventSource)
    {
        <span style="color:#008000;">// the listener can just listen for one event source. </span>
        <span style="color:#008000;">// Detach the previous event source</span>
        <span style="color:#0000ff;">this</span>.Detach();

        <span style="color:#008000;">// keep weak-reference to the the event source</span>
        <span style="color:#0000ff;">this</span>._weakEventSource = <span style="color:#0000ff;">new</span> WeakReference(eventSource);

        TSource eventObject = eventSource <span style="color:#0000ff;">as</span> TSource;
        <span style="color:#0000ff;">if</span> (eventObject != <span style="color:#0000ff;">null</span>)
        {
           var weakListener = CreateWeakEventListenerInternal(eventObject);

           <span style="color:#0000ff;">if</span> (weakListener == <span style="color:#0000ff;">null</span>)
              <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> InvalidOperationException(&quot;<span style="color:#8b0000;">The method CreateWeakEventListener must return a value.</span>&quot;);

           <span style="color:#008000;">// store the weak-listener as weak reference (for Detach method only)</span>
           _weakListener = <span style="color:#0000ff;">new</span> WeakReference(weakListener);
        }
    }

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// Does some debug-time checks and creates the weak event listener.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#808080;">/// &lt;param name=&quot;eventObject&quot;&gt;The event source instance&lt;/param&gt;</span>
    <span style="color:#808080;">/// &lt;returns&gt;Return the weak event listener instance&lt;/returns&gt;</span>
    <span style="color:#0000ff;">private</span> WeakEventListenerBase CreateWeakEventListenerInternal(TSource eventObject)
    {
        #region Debug time checks

        <span style="color:#008000;">// do some implementation checks when a debugger is attached</span>
        <span style="color:#0000ff;">if</span> (Debugger.IsAttached)
        {
            <span style="color:#008000;">// search in each type separately unitl we reach the type WeakEventSourceBase </span>
            <span style="color:#008000;">//(because Reflection can not return private members in FlattenHierarchy.</span>
            Type type = <span style="color:#0000ff;">this</span>.GetType();
            <span style="color:#0000ff;">while</span> ((!type.IsGenericType || type.GetGenericTypeDefinition()                                         != <span style="color:#0000ff;">typeof</span>(WeakEventSourceBase&lt;&gt;)) &amp;&amp; type != <span style="color:#0000ff;">typeof</span>(<span style="color:#0000ff;">object</span>))
            {
                BindingFlags bindingFlags = BindingFlags.Public |
                                            BindingFlags.NonPublic |
                                            BindingFlags.Instance |
                                            BindingFlags.Static |
                                            BindingFlags.DeclaredOnly;

                <span style="color:#008000;">// get fields expect fields marked with CompilerGeneratedAttribute or derived                 // from Delegate (events are delegate fields)</span>
                var queryFields = from f <span style="color:#0000ff;">in</span> type.GetFields(bindingFlags)
                    where f.GetCustomAttributes(<span style="color:#0000ff;">typeof</span>(CompilerGeneratedAttribute),<span style="color:#0000ff;">true</span>).Count()==0 &amp;&amp;
                          !f.FieldType.IsSubclassOf(<span style="color:#0000ff;">typeof</span>(Delegate))
                          select f.Name;

                <span style="color:#008000;">// get properties</span>
                var queryProperties = from f <span style="color:#0000ff;">in</span> type.GetProperties(bindingFlags)
                                      select f.Name;

                var query = queryFields.Union(queryProperties);

                <span style="color:#008000;">// The EventWrapper is intended to be used as a weak-event-wrapper. One should not add </span>
                <span style="color:#008000;">// additional members to this class, because of the possibilty to store the </span>
                <span style="color:#008000;">// WeakEventListener reference to a member.                // Is this the case the memory leak can still occur. </span>
                <span style="color:#008000;">// Therefore, if any field or property is implemented, throw an exception as warning.</span>
                <span style="color:#0000ff;">if</span> (query.Count() &gt; 0)
                {
                   <span style="color:#008000;">// note: MessageBox.Show blocks unit tests</span>
                   <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> InvalidOperationException(<span style="color:#0000ff;">string</span>.Format(&quot;<span style="color:#8b0000;">You should not add any other “ +                             “implementation than overriding methods in the class {0}, because of “ +</span></pre>
<pre><span style="color:#8b0000;">                             “possible memory you can get within your application.</span>&quot;, type.Name));
                }

                <span style="color:#008000;">// continue search in base type</span>
                type = type.BaseType;
            }
        }

        #endregion

        <span style="color:#008000;">// create weak event listener</span>
        <span style="color:#0000ff;">return</span> CreateWeakEventListener(eventObject);
    }

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// When overridden in a derived class, it creates the weak event     /// listener for the given event source.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#808080;">/// &lt;param name=&quot;eventObject&quot;&gt;The event source instance to listen for an event&lt;/param&gt;</span>
    <span style="color:#808080;">/// &lt;returns&gt;Return the weak event listener instance&lt;/returns&gt;</span>
    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">abstract</span> WeakEventListenerBase CreateWeakEventListener(TSource eventObject);

    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// Detaches the event from the event source.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> Detach()
    {
        <span style="color:#0000ff;">if</span> (_weakListener != <span style="color:#0000ff;">null</span>)
        {
            <span style="color:#008000;">// do it the GC safe way, because an object could potentially be reclaimed </span>
            <span style="color:#008000;">// for garbage collection immediately after the IsAlive property returns true</span>
            WeakEventListenerBase target = _weakListener.Target <span style="color:#0000ff;">as</span> WeakEventListenerBase;
            <span style="color:#0000ff;">if</span> (target != <span style="color:#0000ff;">null</span>)
                target.Detach();
        }

        _weakEventSource = <span style="color:#0000ff;">null</span>;
        _weakListener = <span style="color:#0000ff;">null</span>;
    }
}</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/380/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/380/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=380&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/17/weakeventsource-implementation-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/image2.png?w=68&#38;h=68" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Be careful when using WeakReference.IsAlive</title>
		<link>http://blog.thekieners.com/2010/02/16/be-careful-when-using-weakreference-isalive/</link>
		<comments>http://blog.thekieners.com/2010/02/16/be-careful-when-using-weakreference-isalive/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 09:44:08 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/16/be-careful-when-using-weakreference-isalive/</guid>
		<description><![CDATA[The property WeakReference.IsAlive returns true when the target instance to which the WeakReference is pointing to is alive. While IsAlive retuns true there is no guarantee that the Target was not collected in the meantime, because the GC can run at any time between any instructions. The following code can run into a NullReferenceException.
if (_weaRef.IsAlive)
{
 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=375&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>The property WeakReference.IsAlive returns true when the target instance to which the WeakReference is pointing to is alive. While IsAlive retuns true there is no guarantee that the Target was not collected in the meantime, because the GC can run at any time between any instructions. The following code can run into a NullReferenceException.</p>
<pre><span style="color:#0000ff;">if</span> (_weaRef.IsAlive)
{
    MyClass obj = (MyClass)_weaRef.Target;
    var val = obj.ToString();
}
</pre>
<p>The correct usage pattern with the WeakReference&nbsp; should be as following:</p>
<pre><span style="color:#008000;">// create a temporary reference to the target</span>
MyClass obj = _weaRef.Target <span style="color:#0000ff;">as</span> MyClass;
<span style="color:#008000;">// when not null then the target is alive</span>
<span style="color:#0000ff;">if</span> (obj != <span style="color:#0000ff;">null</span>)
{
   var val = obj.ToString();
}
</pre>
<pre>&nbsp;</pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.isalive.aspx" target="_blank">MSDN documentation</a> declares this problem in the Remarks section as following:<em> “Because an object could potentially be reclaimed for garbage collection immediately after the IsAlive property returns true, using this property is not recommended unless you are testing only for a false return value.”<br /></em><br /><strong>Update</strong>: I found this <a href="http://blogs.msdn.com/clyon/archive/2006/04/20/580255.aspx" target="_blank">blog post</a> from Chris Lvon in which he explains the problem in detail.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/375/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/375/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/375/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=375&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/16/be-careful-when-using-weakreference-isalive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple Weak Event Listener for Silverlight</title>
		<link>http://blog.thekieners.com/2010/02/11/simple-weak-event-listener-for-silverlight/</link>
		<comments>http://blog.thekieners.com/2010/02/11/simple-weak-event-listener-for-silverlight/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 06:30:31 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/11/simple-weak-event-listener-for-silverlight/</guid>
		<description><![CDATA[The problem
When using normal CLR events, registering an event handler creates a strong reference from the event source to the listening object. 
 
If the event-source (our ViewModel) has a longer lifetime than the listener and the listener gets released from the hosting app (in our case the visual tree) then it can’t be garbage [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=357&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<h2><b>The problem</b></h2>
<p>When using normal CLR events, registering an event handler creates a strong reference from the event source to the listening object. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image0021.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image002" border="0" alt="clip_image002" src="http://bkiener.files.wordpress.com/2010/02/clip_image002_thumb1.jpg?w=468&#038;h=354" width="468" height="354" /></a> </p>
<p>If the event-source (our ViewModel) has a longer lifetime than the listener and the listener gets released from the hosting app (in our case the visual tree) then it can’t be garbage collected, because the long living event-source instance has still a reference to the listener through the delegate. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image0041.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image004" border="0" alt="clip_image004" src="http://bkiener.files.wordpress.com/2010/02/clip_image004_thumb1.jpg?w=438&#038;h=375" width="438" height="375" /></a> </p>
<p>Unfortunately, visual tree elements don’t provide an UnLoaded event. So I’m not able to unregister the event handler from the event-source. For example when using the event-source for multiple pages as listeners these are alive until the event source gets released. This is a hidden memory leak in our Silverlight application. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image0061.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image006" border="0" alt="clip_image006" src="http://bkiener.files.wordpress.com/2010/02/clip_image006_thumb1.jpg?w=439&#038;h=381" width="439" height="381" /></a> </p>
<p>It is not something new and there are several solutions out there. Most of the solutions using Reflection or dynamic code generation via Reflection.Emit which is not working in Silverlight because of limited reflection permission in Silverlight or it suffer from performance issues. </p>
<p>But how does the Silverlight Toolkit Team deal with this problem? For example, listening for INotifyPropertyChanged or INotifyCollectionChanged in any control is a common task when implementing a custom control. </p>
<h2><b>The solution</b></h2>
<p>Indeed, the Silverlight Toolkit source contains a very simple solution for this problem. The class is called WeakEventListener but its visibility is internal. I just made a copy of the class (thanks to the Microsoft Public License) to use it in our project. </p>
<p>When using this class you should pay attention to two implementation detail otherwise the application still has memory leaks (it think this is the reason why Microsoft did not make the class public). I try to explain it in the rest of this post. </p>
<h2><b>How it works</b></h2>
<p>The WeakEventListener operates as an instance between the event-source and the listener and contains the event handling part. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image0081.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image008" border="0" alt="clip_image008" src="http://bkiener.files.wordpress.com/2010/02/clip_image008_thumb1.jpg?w=441&#038;h=383" width="441" height="383" /></a> </p>
<p>The WeakEventListener associates the listener instance via a WeakReference<b>. It’s very import that the listener just creates the WeakEventListener instance but never holds a reference to it.</b> This together ensures that the listener can be garbage collected when the App instance releases the listener. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image0101.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image010" border="0" alt="clip_image010" src="http://bkiener.files.wordpress.com/2010/02/clip_image010_thumb1.jpg?w=445&#038;h=385" width="445" height="385" /></a> </p>
<h2><b>How to use in code</b></h2>
<pre><span style="color:#008000;">// register for event (weak pattern)</span>
EventSource longLivingInstance = <span style="color:#0000ff;">this</span>.DataContext <span style="color:#0000ff;">as</span> EventSource;

<span style="color:#008000;">// create WeakEventListener. Pass Listener and EventSource instance to it.</span>
var weakListener = <span style="color:#0000ff;">new</span> WeakEventListener&lt;Listener, EventSource,                                          PropertyChangedEventArgs&gt;(<span style="color:#0000ff;">this</span>, longLivingInstance);
<span style="color:#008000;">// register handler</span>
longLivingInstance.PropertyChanged += weakListener.OnEvent;
<span style="color:#008000;">// define event handler to handle the event.</span>
weakListener.OnEventAction = (instance, source, e) =&gt;
{
    <span style="color:#008000;">// event handling code</span>
    instance.longLivingInstance_PropertyChanged(instance, e);
};
<span style="color:#008000;">// define action to detach the handler</span>
weakListener.OnDetachAction = (listener, source) =&gt;
{
    <span style="color:#008000;">// unregister handler</span>
    source.PropertyChanged -= listener.OnEvent;
};
<span style="color:#008000;">// ensure there is no reference from the listener to the weakListener</span>
weakListener = <span style="color:#0000ff;">null</span>;</pre>
<h2><b>Step-by-Step explained</b></h2>
<p>First create an instance of the WeakEventListener with the relevant type arguments from the Listener, EventSource and EventArgs.</p>
<pre><span style="color:#008000;">// create WeakEventListener. Pass Listener and EventSource instance to it.</span>
var weakListener = <span style="color:#0000ff;">new</span> WeakEventListener&lt;Listener, EventSource,                                          PropertyChangedEventArgs&gt;(<span style="color:#0000ff;">this</span>, longLivingInstance);</pre>
<pre>&#160;</pre>
<p>As next, register the OnEvent method from the weakListener as event-handler.</p>
<pre><span style="color:#008000;">// register handler</span>
longLivingInstance.PropertyChanged += weakListener.OnEvent;</pre>
<pre>&#160;</pre>
<p>Then defining the event handler method an assign it to the OnEventAction delegate. </p>
<pre><span style="color:#008000;">// define event handler code.</span>
weakListener.OnEventAction = (instance, source, e) =&gt;
{
    <span style="color:#008000;">// event handling code</span>
    instance.longLivingInstance_PropertyChanged(instance, e);
};</pre>
<p><b>The event handler method must be static.</b> Why this is important? The OnEventAction is a delegate to a method and this method defines the action when the event is raising. It is important that the delegate to this method has no Target set and this is the case when the target method is static. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image00251.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image002[5]" border="0" alt="clip_image002[5]" src="http://bkiener.files.wordpress.com/2010/02/clip_image0025_thumb1.jpg?w=868&#038;h=111" width="868" height="111" /></a> </p>
<p>How it works with lambda statement? When writing a lambda statement, the compiler generates an anonymous method which is static: </p>
<pre>[CompilerGenerated]
<span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> &lt;Listener_Loaded&gt;b__0(Listener instance, <span style="color:#0000ff;">object</span> source, PropertyChangedEventArgs e)
{
    instance.longLivingInstance_PropertyChanged(instance, e);
}</pre>
<pre>&#160;</pre>
<p>But when one accesses any instance member inside the OnEventAction method then the compiler generates an instance method instead of a static.</p>
<pre>[CompilerGenerated]
<span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> &lt;Listener_Loaded&gt;b__0(Listener instance, <span style="color:#0000ff;">object</span> source, PropertyChangedEventArgs e)
{
    <span style="color:#0000ff;">this</span>.longLivingInstance_PropertyChanged(instance, e);
} </pre>
<pre>&#160;</pre>
<p>Because of this small difference the delegate has now a reference back to the listener and the memory leak still remains (only with a little more code…) </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image00271.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image002[7]" border="0" alt="clip_image002[7]" src="http://bkiener.files.wordpress.com/2010/02/clip_image0027_thumb1.jpg?w=470&#038;h=439" width="470" height="439" /></a> </p>
<p>The debugger shows it clearly. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/clip_image00461.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="clip_image004[6]" border="0" alt="clip_image004[6]" src="http://bkiener.files.wordpress.com/2010/02/clip_image0046_thumb1.jpg?w=923&#038;h=115" width="923" height="115" /></a> </p>
<p>This makes the detail whether the WeakEventListener works correctly or not. Therefore, I extended the original WeakEventListener code to prevent this mistake. The OnEventAction property checks in its setter whether the assigned delegate pointing to a static method or not.</p>
<pre>&#160;</pre>
<pre><span style="color:#0000ff;">public</span> Action&lt;TInstance, <span style="color:#0000ff;">object</span>, TEventArgs&gt; OnEventAction
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _onEventAction; }
    <span style="color:#0000ff;">set</span>
    {
        <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">value</span> != <span style="color:#0000ff;">null</span> &amp;&amp; !<span style="color:#0000ff;">value</span>.Method.IsStatic)
            <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentException(&quot;<span style="color:#8b0000;">OnEventAction method must be static otherwise the </span>&quot; +
                                        &quot;<span style="color:#8b0000;">event WeakEventListner class does not prevent memory leaks.</span>&quot;);

        _onEventAction = <span style="color:#0000ff;">value</span>;
    }
}</pre>
<pre>&#160;</pre>
<pre>Lastly, the weakListener needs an action to unregister the event handler.</pre>
<pre>&#160;</pre>
<pre><span style="color:#008000;">// define action to detach the handler</span>
weakListener.OnDetachAction = (listener, source) =&gt;
{
    <span style="color:#008000;">// unregister handler</span>
    source.PropertyChanged -= listener.OnEvent;
};</pre>
<pre>&#160;</pre>
<p>The OnDetachAction is called when one calls the Detach method on the weakListener or when the listener isn’t alive anymore and the event-source is raising events. Here I did another small change in the source code: the OnDetachAction provides the event-source instance as the second parameter. With this the WeakEventListener instance can guarantee to unregister the source-event even though all others had released the EventSource. In other words the WeakEventListener instance can unregisters itself from the EventSource. To get a safety implementation of this rule the OnDetachAction property does the same static-method check as the OnEventAction property. </p>
<h2>Summary</h2>
<p>The Silverlight Toolkit contains an excellent implementation of a WeakEventListener. It doesn’t use reflection or dynamic assembly generation, so you don’t bother with performance or security problems. The only problem I see is that it can be used incorrectly. Therefore, I slightly modified the WeakEventListener with some runtime checks to prevent these mistakes. </p>
<p>In a next post I’m going to document an additional wrapper-pattern I’ve build around the WeakEventListener. The wrapper is designed as an easy to use weak event listener for a specify event source such as the common PropertyChanged and CollectionChanged events from the INotifyPropertyChanged and INotifyCollectionChanged interfaces.</p>
<pre>TestViewModel longLivingInstance = <span style="color:#0000ff;">new</span> TestViewModel();
NotifyPropertyChangedListener listener = <span style="color:#0000ff;">new</span> NotifyPropertyChangedListener(longLivingInstance);
listener.PropertyChanged += <span style="color:#0000ff;">new</span> PropertyChangedEventHandler(listener_PropertyChanged);</pre>
<p>&#160;</p>
<p>And I want to explain why for us the weak event pattern is such much important when writing custom controls or making async service calls.</p>
<h2>Source Code</h2>
<p><a href="http://files.thekieners.com/blogcontent/SimpleWeakEventPattern.zip" target="_blank">Here you can find the full source code.</a></p>
<p><a href="http://files.thekieners.com/blogcontent/SimpleWeakEventPattern.zip" target="_blank"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/02/image2.png?w=68&#038;h=68" width="68" height="68" /></a> </p>
<p>Modified WeakEventListener class (original is in Silverlight Toolkit):</p>
<pre><span style="color:#008000;">//-----------------------------------------------------------------------</span>
<span style="color:#008000;">//  This source is a slightly modified version from the WeakEventListner</span>
<span style="color:#008000;">//  in the Silverlight Toolkit Source (www.codeplex.com/Silverlight)</span>
<span style="color:#008000;">//---------------------------Original Source-----------------------------</span>
<span style="color:#008000;">// &lt;copyright company=&quot;Microsoft&quot;&gt;</span>
<span style="color:#008000;">//      (c) Copyright Microsoft Corporation.</span>
<span style="color:#008000;">//      This source is subject to the Microsoft Public License (Ms-PL).</span>
<span style="color:#008000;">//      Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.</span>
<span style="color:#008000;">//      All other rights reserved.</span>
<span style="color:#008000;">// &lt;/copyright&gt;</span>
<span style="color:#008000;">//-----------------------------------------------------------------------</span>

<span style="color:#0000ff;">using</span> System.Diagnostics.CodeAnalysis;
<span style="color:#0000ff;">using</span> System.Diagnostics;

<span style="color:#0000ff;">namespace</span> System.Windows.Controls
{
    <span style="color:#808080;">/// &lt;summary&gt;</span>
    <span style="color:#808080;">/// Implements a weak event listener that allows the owner to be garbage</span>
    <span style="color:#808080;">/// collected if its only remaining link is an event handler.</span>
    <span style="color:#808080;">/// &lt;/summary&gt;</span>
    <span style="color:#808080;">/// &lt;typeparam name=&quot;TInstance&quot;&gt;Type of rootInstance listening for the event.&lt;/typeparam&gt;</span>
    <span style="color:#808080;">/// &lt;typeparam name=&quot;TSource&quot;&gt;Type of source for the event.&lt;/typeparam&gt;</span>
    <span style="color:#808080;">/// &lt;typeparam name=&quot;TEventArgs&quot;&gt;Type of event arguments for the event.&lt;/typeparam&gt;</span>
    <span style="color:#0000ff;">internal</span> <span style="color:#0000ff;">class</span> WeakEventListener&lt;TInstance, TSource, TEventArgs&gt; where TInstance : <span style="color:#0000ff;">class</span>
    {

        #region Fields

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// WeakReference to the rootInstance listening for the event.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> WeakReference _weakInstance;

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// To hold a reference to source object. With this instance the WeakEventListener </span>
        <span style="color:#808080;">/// // can guarantee that the handler get unregistered when listener is released.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> TSource _source;

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Delegate to the method to call when the event fires.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> Action&lt;TInstance, <span style="color:#0000ff;">object</span>, TEventArgs&gt; _onEventAction;

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Delegate to the method to call when detaching from the event.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">private</span> Action&lt;WeakEventListener&lt;TInstance, TSource, TEventArgs&gt;, TSource&gt; _onDetachAction;

        #endregion

        #region Ctor

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Initializes a new instances of the WeakEventListener class.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#808080;">/// &lt;param name=&quot;rootInstance&quot;&gt;Instance subscribing to the event.&lt;/param&gt;</span>
        <span style="color:#0000ff;">public</span> WeakEventListener(TInstance instance, TSource source)
        {
            <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">null</span> == instance)
            {
                <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentNullException(&quot;<span style="color:#8b0000;">instance</span>&quot;);
            }

            <span style="color:#0000ff;">if</span> (source == <span style="color:#0000ff;">null</span>)
                <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentNullException(&quot;<span style="color:#8b0000;">source</span>&quot;);

            _weakInstance = <span style="color:#0000ff;">new</span> WeakReference(instance);
            <span style="color:#0000ff;">this</span>._source = source;
        }

        #endregion

        #region Properties

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Gets or sets the method to call when the event fires.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">public</span> Action&lt;TInstance, <span style="color:#0000ff;">object</span>, TEventArgs&gt; OnEventAction
        {
            <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _onEventAction; }
            <span style="color:#0000ff;">set</span>
            {
                <span style="color:#008000;">// CHANGED: NEVER REMOVE THIS CHECK. IT CAN CAUSE A MEMORY LEAK.</span>
                <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">value</span> != <span style="color:#0000ff;">null</span> &amp;&amp; !<span style="color:#0000ff;">value</span>.Method.IsStatic)
                    <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentException(&quot;<span style="color:#8b0000;">OnEventAction method must be static </span>&quot;+
                              &quot;<span style="color:#8b0000;">otherwise the event WeakEventListner class does not prevent memory leaks.</span>&quot;);

                _onEventAction = <span style="color:#0000ff;">value</span>;
            }
        }

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Gets or sets the method to call when detaching from the event.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">internal</span> Action&lt;WeakEventListener&lt;TInstance, TSource, TEventArgs&gt;, TSource&gt; OnDetachAction
        {
            <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _onDetachAction; }
            <span style="color:#0000ff;">set</span>
            {

                <span style="color:#008000;">// CHANGED: NEVER REMOVE THIS CHECK. IT CAN CAUSE A MEMORY LEAK.</span>
                <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">value</span> != <span style="color:#0000ff;">null</span> &amp;&amp; !<span style="color:#0000ff;">value</span>.Method.IsStatic)
                    <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> ArgumentException(&quot;<span style="color:#8b0000;">OnDetachAction method must be static otherwise </span>&quot; +
                               &quot;<span style="color:#8b0000;">the event WeakEventListner cannot guarantee to unregister the handler.</span>&quot;);

                _onDetachAction = <span style="color:#0000ff;">value</span>;
            }
        }

        #endregion

        #region Public methods

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Handler for the subscribed event calls OnEventAction to handle it.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#808080;">/// &lt;param name=&quot;source&quot;&gt;Event source.&lt;/param&gt;</span>
        <span style="color:#808080;">/// &lt;param name=&quot;eventArgs&quot;&gt;Event arguments.&lt;/param&gt;</span>
        <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> OnEvent(<span style="color:#0000ff;">object</span> source, TEventArgs eventArgs)
        {
            TInstance target = (TInstance)_weakInstance.Target;
            <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">null</span> != target)
            {
                <span style="color:#008000;">// Call registered action</span>
                <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">null</span> != OnEventAction)
                {
                    OnEventAction(target, source, eventArgs);
                }
            }
            <span style="color:#0000ff;">else</span>
            {
                <span style="color:#008000;">// Detach from event</span>
                Detach();
            }
        }

        <span style="color:#808080;">/// &lt;summary&gt;</span>
        <span style="color:#808080;">/// Detaches from the subscribed event.</span>
        <span style="color:#808080;">/// &lt;/summary&gt;</span>
        <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> Detach()
        {
            <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">null</span> != OnDetachAction)
            {
                <span style="color:#008000;">// CHANGED: Passing the source instance also, because of static event handlers</span>
                OnDetachAction(<span style="color:#0000ff;">this</span>, <span style="color:#0000ff;">this</span>._source);
                OnDetachAction = <span style="color:#0000ff;">null</span>;
            }
        }

        #endregion
    }
}</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/357/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/357/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/357/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/357/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/357/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=357&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/11/simple-weak-event-listener-for-silverlight/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image002_thumb1.jpg" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image004_thumb1.jpg" medium="image">
			<media:title type="html">clip_image004</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image006_thumb1.jpg" medium="image">
			<media:title type="html">clip_image006</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image008_thumb1.jpg" medium="image">
			<media:title type="html">clip_image008</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image010_thumb1.jpg" medium="image">
			<media:title type="html">clip_image010</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image0025_thumb1.jpg" medium="image">
			<media:title type="html">clip_image002[5]</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image0027_thumb1.jpg" medium="image">
			<media:title type="html">clip_image002[7]</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/clip_image0046_thumb1.jpg" medium="image">
			<media:title type="html">clip_image004[6]</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/image2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Databinding Multi-Series Charts</title>
		<link>http://blog.thekieners.com/2010/02/07/databinding-multi-series-charts/</link>
		<comments>http://blog.thekieners.com/2010/02/07/databinding-multi-series-charts/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 16:12:46 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/02/07/databinding-multi-series-charts/</guid>
		<description><![CDATA[
I am working on a Silverlight project, where we doing straight MVVM. Binding the Chart control included in the Silverlight Toolkit (www.codeplex.com/Silverlight) to a ViewModel is quite simple. But what when I want to bind a collection of different &#8220;graphs&#8221; each with an own collection of data-points to a single chart? 
Suppose a line-chart with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=338&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[</p>
<p>I am working on a Silverlight project, where we doing straight MVVM. Binding the Chart control included in the Silverlight Toolkit (<a href="http://www.codeplex.com/Silverlight">www.codeplex.com/Silverlight</a>) to a ViewModel is quite simple. But what when I want to bind a collection of different &#8220;graphs&#8221; each with an own collection of data-points to a single chart? </p>
<p>Suppose a line-chart with dynamically changing the numbers of lines.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/image.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/02/image_thumb.png?w=490&#038;h=235" width="490" height="235"></a> </p>
<p>&nbsp;</p>
<p>I decided to use a DataTemplate similar to the ItemsTemplate in the ItemsControl class. <br />So, I created the MultiChart control as sub class of the Silverlight Toolkit Chart control.</p>
<pre><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> MutliChart : System.Windows.Controls.DataVisualization.Charting.Chart
{
}
</pre>
<pre>&nbsp;</pre>
<p>Then I added two dependency properties (full source code is attached)
<pre><span style="color:#0000ff;">public</span> IEnumerable SeriesSource
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (IEnumerable)GetValue(SeriesSourceProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(SeriesSourceProperty, <span style="color:#0000ff;">value</span>); }
}

<span style="color:#0000ff;">public</span> DataTemplate SeriesTemplate
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (DataTemplate)GetValue(SeriesTemplateProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(SeriesTemplateProperty, <span style="color:#0000ff;">value</span>); }
}</pre>
<p>&nbsp;
<p>Now, I’m able to databind my multi-series datasource to the SeriesSource property similar as one binds the ItemsSource to an ItemsControl or a DataGrid control. The MultiChart control generates DataSeries items based on the SeriesTemplate. The series are now full bindable to a dynamic list in the ViewModel.</p>
<p>The XAML locks like this:
<pre>    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart</span> <span style="color:#ff0000;">SeriesSource</span>=<span style="color:#0000ff;">"{Binding MySalesData}"</span> <span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart.SeriesTemplate</span> <span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#0000ff;">&gt;</span>
                <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">chartingToolkit</span>:<span style="color:#800000;">LineSeries</span>
			       <span style="color:#ff0000;">Title</span>=<span style="color:#0000ff;">"{Binding Title}"</span>
			       <span style="color:#ff0000;">ItemsSource</span>=<span style="color:#0000ff;">"{Binding Sales}"</span>
			       <span style="color:#ff0000;">IndependentValueBinding</span>=<span style="color:#0000ff;">"{Binding SalesName}"</span>
			       <span style="color:#ff0000;">DependentValueBinding</span>=<span style="color:#0000ff;">"{Binding SalesTotal}"</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart.SeriesTemplate</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart</span><span style="color:#0000ff;">&gt;</span>
</pre>
<p>This implementation is similar to the content model in other controls i.e., Content and ContentTemplate, Header and HeaderTemplate, Items or ItemsSource and ItemTemplate, etc.</p>
<p>But what if I want to have different chart-series in the same chart such as column-series and line-series databound to the ViewModel? </p>
<p><a href="http://bkiener.files.wordpress.com/2010/02/image1.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/02/image_thumb1.png?w=512&#038;h=212" width="512" height="212"></a> </p>
<p>What I need is a different DataTemplate per item type in the data source. Unfortunately Silverlight does not support typed data-templates natively. WPF answers this problem with DataTemplateSelector (and the ContentTemplateSelector, HeaderTemplateSelector, and ItemTemplateSelector properties).&nbsp; Silverlight doesn’t yet support it, but we can achieve the same effect after a little more code.</p>
<p>So, I added another dependency property called SeriesTemplateSelector.
<pre><span style="color:#0000ff;">public</span> DataTemplateSelector SeriesTemplateSelector
{
    <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> (DataTemplateSelector)GetValue(SeriesTemplateSelectorProperty); }
    <span style="color:#0000ff;">set</span> { SetValue(SeriesTemplateSelectorProperty, <span style="color:#0000ff;">value</span>); }
}
</pre>
<p>&nbsp;
<p>The class DataTemplateSelector does not exists in Silverlight. So, I just copied the DataTemplateSelector base class from the WPF assembly (via Reflector).
<pre><span style="color:#008000;">// code from WPF</span>

<span style="color:#0000ff;">using</span> System;
<span style="color:#0000ff;">using</span> System.Windows;

<span style="color:#0000ff;">namespace</span> System.Windows.Controls
{
    <span style="color:#008000;">// Summary: </span>
    <span style="color:#008000;">// Provides a way to choose a System.Windows.DataTemplate based on the data </span>
    <span style="color:#008000;">// object and the data-bound element. </span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> DataTemplateSelector
    {
        <span style="color:#008000;">// Summary: </span>
        <span style="color:#008000;">// Initializes a new instance of the System.Windows.Controls.DataTemplateSelector </span>
        <span style="color:#008000;">// class. </span>
        <span style="color:#0000ff;">public</span> DataTemplateSelector()
        {
        }

        <span style="color:#008000;">// Summary: </span>
        <span style="color:#008000;">// When overridden in a derived class, returns a System.Windows.DataTemplate </span>
        <span style="color:#008000;">// based on custom logic. </span>
        <span style="color:#008000;">// </span>
        <span style="color:#008000;">// Parameters: </span>
        <span style="color:#008000;">// item: </span>
        <span style="color:#008000;">// The data object for which to select the template. </span>
        <span style="color:#008000;">// </span>
        <span style="color:#008000;">// container: </span>
        <span style="color:#008000;">// The data-bound object. </span>
        <span style="color:#008000;">// </span>
        <span style="color:#008000;">// Returns: </span>
        <span style="color:#008000;">// Returns a System.Windows.DataTemplate or null. The default value is null. </span>
        <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> DataTemplate SelectTemplate(<span style="color:#0000ff;">object</span> item, DependencyObject container)
        {
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
        }
    }
}
</pre>
<p>&nbsp;
<p>If the SeriesTemplateSelector is set then the MultiChart control selects its data-template with this instance.</p>
<p>At the end my XAML looks like this:
<pre><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">UserControl</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">UserControl.Resources</span> <span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Key</span>=<span style="color:#0000ff;">"chartTemplateSelector"</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector.SalesTemplate</span><span style="color:#0000ff;">&gt;</span>
                <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#0000ff;">&gt;</span>
                    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">chartingToolkit</span>:<span style="color:#800000;">LineSeries</span>
                                    <span style="color:#ff0000;">Title</span>=<span style="color:#0000ff;">"{Binding SalesName}"</span>
                                    <span style="color:#ff0000;">ItemsSource</span>=<span style="color:#0000ff;">"{Binding SalesTotals}"</span>
                                    <span style="color:#ff0000;">IndependentValueBinding</span>=<span style="color:#0000ff;">"{Binding Date}"</span>
                                    <span style="color:#ff0000;">DependentValueBinding</span>=<span style="color:#0000ff;">"{Binding SalesTotal}"</span> <span style="color:#0000ff;">/&gt;</span>
                <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector.SalesTemplate</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector.MedianTemplate</span><span style="color:#0000ff;">&gt;</span>
                <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">DataTemplate</span> <span style="color:#0000ff;">&gt;</span>
                    <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">chartingToolkit</span>:<span style="color:#800000;">ColumnSeries</span>
                                    <span style="color:#ff0000;">Title</span>=<span style="color:#0000ff;">"{Binding SalesName}"</span>
                                    <span style="color:#ff0000;">ItemsSource</span>=<span style="color:#0000ff;">"{Binding SalesTotals}"</span>
                                    <span style="color:#ff0000;">IndependentValueBinding</span>=<span style="color:#0000ff;">"{Binding Date}"</span>
                                    <span style="color:#ff0000;">DependentValueBinding</span>=<span style="color:#0000ff;">"{Binding SalesTotal}"</span> <span style="color:#0000ff;">/&gt;</span>
                <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">DataTemplate</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector.MedianTemplate</span><span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">SeriesTemplateSelector</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">UserControl.Resources</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">"LayoutRoot"</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart</span> <span style="color:#ff0000;">SeriesSource</span>=<span style="color:#0000ff;">"{Binding SalesDataWithMedian}"</span>
                              <span style="color:#ff0000;">SeriesTemplateSelector</span>=<span style="color:#0000ff;">"{StaticResource chartTemplateSelector}"</span>
                              <span style="color:#ff0000;">Title</span>=<span style="color:#0000ff;">"Dynamic Multi Lines with different DataTemplates"</span><span style="color:#0000ff;">&gt;</span>

            <span style="color:#0000ff;">&lt;/</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MultiChart</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">UserControl</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&nbsp;
<p>Here the implementation of SeriesTemplateSelector class:
<pre>   <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> SeriesTemplateSelector : DataTemplateSelector
    {
        <span style="color:#0000ff;">public</span> DataTemplate SalesTemplate { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }
        <span style="color:#0000ff;">public</span> DataTemplate MedianTemplate { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }

        <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> DataTemplate SelectTemplate(<span style="color:#0000ff;">object</span> item, DependencyObject container)
        {

            <span style="color:#0000ff;">if</span> (item <span style="color:#0000ff;">is</span> SalesPerformance)
            {
                SalesPerformance salesPerf = item <span style="color:#0000ff;">as</span> SalesPerformance;

                <span style="color:#0000ff;">if</span> (salesPerf.SalesName == "<span style="color:#8b0000;">Median</span>")
                {
                    <span style="color:#0000ff;">return</span> MedianTemplate;
                }
                <span style="color:#0000ff;">else</span>
                {
                    <span style="color:#0000ff;">return</span> SalesTemplate;
                }
            }

            <span style="color:#008000;">// default</span>
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;

        }
    }</pre>
<pre>&nbsp;</pre>
<p>Finally I got a fully bindable mutli-series chart control which provides the same content model as other well-known control such the ItemsControl.</p>
<p><a href="http://files.thekieners.com/blogcontent/MultiChartDemo.zip" target="_blank">Here you can find the source code in a demo project</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/338/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/338/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/338/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/338/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/338/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/338/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/338/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/338/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/338/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/338/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=338&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/02/07/databinding-multi-series-charts/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/02/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Memory leak with focusable UIElement in Silverlight?</title>
		<link>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/</link>
		<comments>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 13:08:00 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/</guid>
		<description><![CDATA[Suppose we have a StackPanel with following controls inside.
        &#60;StackPanel x:Name=&#34;stackpanel&#34; Width=&#34;200&#34;&#62;
            &#60;TextBox /&#62;
            &#60;CheckBox /&#62;
           [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=330&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Suppose we have a StackPanel with following controls inside.</p>
<pre>        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;stackpanel&quot;</span> <span style="color:#ff0000;">Width</span>=<span style="color:#0000ff;">&quot;200&quot;</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">CheckBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ComboBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">controls</span>:<span style="color:#800000;">DatePicker</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MyTextBox</span> <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&#160;</p>
<p>All of them are focusable controls. MyTextBox is a subclass of TextBox as following:</p>
<pre>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> MyTextBox : TextBox
    {
        ~MyTextBox()
        {
            Debug.WriteLine(&quot;<span style="color:#8b0000;">MyTextBox.Finalize</span>&quot;);
        }
    }</pre>
<p>&#160;</p>
<p>Now, if I remove the Children in the stackpanel&#8230;</p>
<pre><span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();</pre>
<p>
  <br />&#8230;all Children gets garbage collected. Everything correct until here.</p>
<p>&#160;</p>
<p>Restart the application. Now set the focus to any element in the stackpanel and stepwise to all others too.<br />
  <br />If I now remove all children from the stackpanel none of them gets garbage collected.</p>
<pre><span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();</pre>
<p>
  <br />Unfortunately, this problem has several negative side effects. We are using the MVVM pattern and when we databind the controls to a ViewModel then the ViewModel is also part of the memory leak, because the binding contains a reference to the ViewModel.</p>
<p>It also doesn&#8217;t help to remove the whole page. I&#8217;ve tested the code within a navigation application with the same result.</p>
<p>&#160;</p>
<h2>Demo Project</h2>
<p>Donwload the <a href="http://files.thekieners.com/blogcontent/PossibleMemoryLeak.zip" target="_blank"><strong>demo project here</strong></a>.</p>
<p>Please note: perhaps you have to run the GC n-times to collect all object, but at the end all elements which had the focus at any time will never be collected neither when you run the GC 1000 times or neither when you release the whole user control.</p>
<p>&#160;</p>
<h2>XAML snapshot</h2>
<pre>    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;LayoutRoot&quot;</span> <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">&quot;White&quot;</span><span style="color:#0000ff;">&gt;</span>

        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;btnRemove&quot;</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">&quot;Remove all&quot;</span> <span style="color:#ff0000;">Click</span>=<span style="color:#0000ff;">&quot;btnRemove_Click&quot;</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;btnCollect&quot;</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">&quot;Run Garbage Collector&quot;</span> <span style="color:#ff0000;">Click</span>=<span style="color:#0000ff;">&quot;btnCollect_Click&quot;</span>  <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span>

        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;stackpanel&quot;</span> <span style="color:#ff0000;">Width</span>=<span style="color:#0000ff;">&quot;200&quot;</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">CheckBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ComboBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">controls</span>:<span style="color:#800000;">DatePicker</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MyTextBox</span> <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span>

    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&#160;</p>
<h2>C# snapshot</h2>
<pre>    <span style="color:#0000ff;">public</span> partial <span style="color:#0000ff;">class</span> MainPage : UserControl
    {
        <span style="color:#0000ff;">private</span> List&lt;WeakReference&gt; weakRefs = <span style="color:#0000ff;">new</span> List&lt;WeakReference&gt;();

        <span style="color:#0000ff;">public</span> MainPage()
        {
            InitializeComponent();

            <span style="color:#008000;">// collect all children to get a weakreference to it</span>
            <span style="color:#0000ff;">foreach</span> (UIElement element <span style="color:#0000ff;">in</span> <span style="color:#0000ff;">this</span>.stackpanel.Children)
                weakRefs.Add(<span style="color:#0000ff;">new</span> WeakReference(element));

            <span style="color:#008000;">// add the view model to the list too</span>
            weakRefs.Add(<span style="color:#0000ff;">new</span> WeakReference(<span style="color:#0000ff;">this</span>.DataContext));
        }

        <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> btnRemove_Click(<span style="color:#0000ff;">object</span> sender, RoutedEventArgs e)
        {
            <span style="color:#008000;">// removing the DataContext forces a rebind of all databound controls. </span>
            <span style="color:#008000;">// This releases the binding-reference from the control to the ViewModel.</span>
            <span style="color:#0000ff;">this</span>.DataContext = <span style="color:#0000ff;">null</span>;

            <span style="color:#008000;">// important: first remove the datacontext and then clear the children </span>
            <span style="color:#008000;">//            otherwise the ViewModel is part of the memory leak.</span>
            <span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();
        }

        <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> btnCollect_Click(<span style="color:#0000ff;">object</span> sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            <span style="color:#008000;">// count how many reference are not collected</span>
            var objectsAlive = (from wr <span style="color:#0000ff;">in</span> weakRefs
                                where wr.IsAlive
                                select wr.Target).ToList();

            Debug.WriteLine(&quot;<span style="color:#8b0000;">Total instances not collected: </span>&quot; + objectsAlive.Count);
            objectsAlive.ForEach(obj =&gt; Debug.WriteLine(&quot;<span style="color:#8b0000;">     </span>&quot; + obj.GetType().Name));
        }

    }

    <span style="color:#008000;">// class to output the finalizing</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> MyTextBox : TextBox
    {
        ~MyTextBox()
        {
            Debug.WriteLine(&quot;<span style="color:#8b0000;">MyTextBox.Finalize</span>&quot;);
        }
    }</pre>
<p>&#160;</p>
<h2>Feedback</h2>
<p>I’ve posted this problem on the silverlight.net forum as a possible bug. <a href="http://forums.silverlight.net/forums/p/158724/355572.aspx" target="_blank"><strong>Check it out here</strong></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/330/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=330&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>
	</item>
		<item>
		<title>My first Microsoft Certification Exam</title>
		<link>http://blog.thekieners.com/2010/01/11/my-first-microsoft-certification-exam/</link>
		<comments>http://blog.thekieners.com/2010/01/11/my-first-microsoft-certification-exam/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 09:50:00 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Exam]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/01/11/my-first-microsoft-certification-exam/</guid>
		<description><![CDATA[Last week I have passed the Microsoft Certification Exam 70-502 &#34;Windows Presentation Foundation Application Development&#34; successfully. After working about 2 year with WPF/Silverlight technology I decided to verify my knowledge with this exam.
Here my result:
 
&#160;
I used the book &#34;MCTS Self-Paced Training Kit&#34; as my main study guide.     My final preparation [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=329&subd=bkiener&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Last week I have passed the Microsoft Certification Exam 70-502 &quot;Windows Presentation Foundation Application Development&quot; successfully. After working about 2 year with WPF/Silverlight technology I decided to verify my knowledge with this exam.</p>
<p>Here my result:</p>
<p><a href="http://bkiener.files.wordpress.com/2010/01/image.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/01/image_thumb.png?w=591&#038;h=427" width="591" height="427" /></a> </p>
<p>&#160;</p>
<p>I used the book &quot;MCTS Self-Paced Training Kit<strong>&quot;</strong> as my main study guide.     <br />My final preparation duration with this book was around one month.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/01/image1.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/01/image_thumb1.png?w=175&#038;h=214" width="175" height="214" /></a> </p>
<p>Next step is to pass the Exam<strong> </strong>70-536 &quot;Microsoft .NET Framework Application Development&quot;.     <br />Let&#8217;s see. Maybe next month.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/329/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&blog=7436128&post=329&subd=bkiener&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/01/11/my-first-microsoft-certification-exam/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/01/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/01/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
	</channel>
</rss>