<?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>Umair&#039;s Blog &#187; C#</title>
	<atom:link href="http://umairsaeed.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://umairsaeed.com</link>
	<description></description>
	<lastBuildDate>Sat, 05 May 2012 21:08:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='umairsaeed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Umair&#039;s Blog &#187; C#</title>
		<link>http://umairsaeed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://umairsaeed.com/osd.xml" title="Umair&#039;s Blog" />
	<atom:link rel='hub' href='http://umairsaeed.com/?pushpress=hub'/>
		<item>
		<title>Incorrect C++ compiler behavior in Visual Studio</title>
		<link>http://umairsaeed.com/2011/01/31/incorrect-c-compiler-behavior-in-visual-studio/</link>
		<comments>http://umairsaeed.com/2011/01/31/incorrect-c-compiler-behavior-in-visual-studio/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 14:36:29 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Compiler]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/2011/01/31/incorrect-c-compiler-behavior-in-visual-studio/</guid>
		<description><![CDATA[[Note: Special credit for this post goes to my colleague Yuliy Gerchikov, who first discovered this issue] As most C++ programmers know, an object that has been constructed via the new expression must be destroyed by calling delete. The delete-expression &#8230; <a href="http://umairsaeed.com/2011/01/31/incorrect-c-compiler-behavior-in-visual-studio/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=172&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>[Note: Special credit for this post goes to my colleague Yuliy Gerchikov, who first discovered this issue]</p>
<p>As most C++ programmers know, an object that has been constructed via the new expression must be destroyed by calling delete. The delete-expression invokes the object&#8217;s destructor which in turn is responsible for clean up tasks. For instance, here&#8217;s some sample code that shows object creation, and then freeing it up via delete:</p>
<p><pre class="brush: cpp;">
	Foo *pF = new Foo();
	// Do some work
	delete pF;
</pre></p>
<p>The <a href="http://http://www.kuzbass.ru:8086/docs/isocpp/expr.html" target="_blank">C++ Specification</a> for delete has this to say:</p>
<p><em>The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.</em></p>
<p><em> delete-expression:<br />
::<sub>opt</sub> delete cast-expression<br />
::<sub>opt</sub> delete [ ] cast-expression<br />
</em></p>
<p><em>The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. <strong>The result has type void.</strong> (emphasis mine)</em></p>
<p>So, given that the delete expression has the return type void, what do you think the C++ compiler should do when it sees the following code:</p>
<p><pre class="brush: cpp;">
	Foo *pF = new Foo();
	// Do some work
	delete delete pF;
</pre></p>
<p>But delete returns void, so it is reasonable to assume that the C++ compilers would throw a fit on the above code, right? Right? Unfortunately, that&#8217;s not always the case.</p>
<p>Let&#8217;s look at some C++ code. I have two user defined types Foo and Bar. The difference between the two types is that I declare and define an explicit destructor for Foo.</p>
<p><pre class="brush: cpp;">
#include &lt;iostream&gt;
class Foo {
	public: ~Foo() { std::cout&lt;&lt;&quot;In dtor&quot;&lt;&lt;std::endl; }
};

class Bar {};

int main(){
	Foo *pf = new Foo();
    delete delete pf;

    Bar *pb = new Bar();
    delete delete pb;

    return 0;
}
</pre></p>
<h5>Listing-1</h5>
</p>
<p>When I compile this using Microsoft&#8217;s cl compiler as it ships with Visual Studio 2010 (Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64) here&#8217;s what I get:</p>
<p><pre class="brush: plain;">
test.cpp(13) : error C2541: 'delete' : cannot delete
 objects that are not pointers
</pre></p>
<p>And here’s the screen shot:</p>
<p><a href="http://umairsd.files.wordpress.com/2011/01/screen-shot-11.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 2px;" title="Screen shot-1" src="http://umairsd.files.wordpress.com/2011/01/screen-shot-1_thumb.png?w=501&h=269" border="0" alt="Screen shot-1" width="501" height="269" /></a></p>
<p>What is going on? Why doesn&#8217;t the compiler complain at both lines 10 and 13? It turns out, if a user-defined type has an explicit destructor, then the Visual Studio compiler happily compiles the double delete expression. It appears that in such a case the compiler violates the C++ specifications as the &#8220;delete ptr-to-type&#8221; returns a non-void pointer instead of void.</p>
<p>Suppose I get my code to compile by getting rid of the offending Bar object (code shown below). When I run my program, it is guaranteed to crash as we are calling delete on a ptr to unallocated space!</p>
<p><pre class="brush: cpp;">
#include &lt;iostream&gt;
class Foo {
	public: ~Foo() { std::cout&lt;&lt;&quot;In dtor&quot;&lt;&lt;std::endl; }
};

int main(){
	Foo *pf = new Foo();
    delete delete pf;		//Uh Oh!

    std::cout&lt;&lt;&quot;Hello world&quot;&lt;&lt;std::endl;
    return 0;
}
</pre></p>
<h5>Listing-2</h5>
</p>
<p>And here&#8217;s the screen shot of the crash. Notice that as expected, the &#8220;<span style="font-family:Courier New;">Hello world</span>&#8221; line never gets executed.</p>
<p><a href="http://umairsd.files.wordpress.com/2011/01/screen-shot-21.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 2px;" title="Screen shot-2" src="http://umairsd.files.wordpress.com/2011/01/screen-shot-2_thumb.png?w=508&h=308" border="0" alt="Screen shot-2" width="508" height="308" /></a></p>
<p>I tried out the same code in gcc (i686-apple-darwin10-gcc-4.2.1), and gcc behaves correctly, i.e. it errors out on both lines 10 and 13 in the listing-1 above.</p>
<p>I am not sure if this behavior of the Visual Studio compiler is intentional. What do you think? Have you encountered any weird C++ compiler behaviors? Please share your thoughts in the comments below.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/172/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=172&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2011/01/31/incorrect-c-compiler-behavior-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/01/screen-shot-1_thumb.png" medium="image">
			<media:title type="html">Screen shot-1</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/01/screen-shot-2_thumb.png" medium="image">
			<media:title type="html">Screen shot-2</media:title>
		</media:content>
	</item>
		<item>
		<title>Code Snippets in Visual Studio 2010</title>
		<link>http://umairsaeed.com/2010/06/22/code-snippets-in-visual-studio-2010/</link>
		<comments>http://umairsaeed.com/2010/06/22/code-snippets-in-visual-studio-2010/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 12:58:46 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/2010/06/22/code-snippets-in-visual-studio-2010/</guid>
		<description><![CDATA[Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code &#8230; <a href="http://umairsaeed.com/2010/06/22/code-snippets-in-visual-studio-2010/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=118&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code during presentations. Instead of typing everything live, I find it far easier to simply add the code block by block using code snippets. </p>
<p>VS 2010 improves the snippet functionality, and makes it easier to create code snippets. There&#8217;s two types of snippets: </p>
<p>- Expansion snippets are inserted at the cursor   <br />- SurroundsWith snippets wraps around selected code</p>
<p>&#160;</p>
<p><strong>Creating a Custom Snippet:     <br /></strong>Let&#8217;s go ahead and create a try-catch-finally Expansion snippet: </p>
<p>- Insert a new XML file to the project and call it TryCatchFinally.snippet. Make sure the file name ends with .snippet </p>
<p>- Right-click on the editor window and select Insert Snippet-&gt;Snippet. This creates a basic XML snippet template as shown below:</p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;CodeSnippet Format=&quot;1.0.0&quot; 
             xmlns=&quot;http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet&quot;&gt;
  &lt;Header&gt;
    &lt;Title&gt;title&lt;/Title&gt;
    &lt;Author&gt;author&lt;/Author&gt;
    &lt;Shortcut&gt;shortcut&lt;/Shortcut&gt;
    &lt;Description&gt;description&lt;/Description&gt;
    &lt;SnippetTypes&gt;
      &lt;SnippetType&gt;SurroundsWith&lt;/SnippetType&gt;
      &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
    &lt;/SnippetTypes&gt;
  &lt;/Header&gt;
  &lt;Snippet&gt;
    &lt;Declarations&gt;
      &lt;Literal&gt;
        &lt;ID&gt;name&lt;/ID&gt;
        &lt;Default&gt;value&lt;/Default&gt;
      &lt;/Literal&gt;
    &lt;/Declarations&gt;
    &lt;Code Language=&quot;XML&quot;&gt;
      &lt;![CDATA[&lt;test&gt;
      &lt;name&gt;$name$&lt;/name&gt;
      $selected$ $end$&lt;/test&gt;]]&gt;
    &lt;/Code&gt;
  &lt;/Snippet&gt;
&lt;/CodeSnippet&gt;
</pre>
</pre>
<p>- As you can see, by default the template contains both snippet types. Since I am creating an Expansion snippet, let&#8217;s go ahead and get rid of the &lt;SnippetType&gt;SurroundsWith&lt;/SnippetType&gt; tag. </p>
<p>- Update the Title to &quot;Try Catch Finally&quot;, Shortcut to &quot;trycf&quot; and Description to &quot;Adds a try-catch-finally block&quot;. </p>
<p>- Literal tag enables us to define editable values that are inserted into the snippet. In the try-catch-finally snippet, we want to allow the user to change the type of the Exception being caught. The ID tag is the name of the editable value so change it to &quot;ExceptionName&quot;. The Default tag specifies the default value for our editable field. I want to catch all exceptions, so change the Default tag&#8217;s value to &quot;Exception&quot;. </p>
<p>- Finally, the code section contains what will be added when the snippet is inserted. Change the language to &quot;CSharp&quot;, and the body to the following:</p>
<pre>
<pre class="brush: xml; auto-links: false;">
    &lt;Code Language=&quot;CSharp&quot;&gt;
      &lt;![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]&gt;
    &lt;/Code&gt;
</pre>
</pre>
<p>- The final version of the TryCatchFinally.snippet file is shown below. For more details about the XML schema, take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms171418%28v=VS.80%29.aspx">MSDN code snippets Schema Reference</a> </p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;CodeSnippet Format=&quot;1.0.0&quot; 
             xmlns=&quot;http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet&quot;&gt;
  &lt;Header&gt;
    &lt;Title&gt;Try Catch Finally&lt;/Title&gt;
    &lt;Author&gt;umair&lt;/Author&gt;
    &lt;Shortcut&gt;trycf&lt;/Shortcut&gt;
    &lt;Description&gt;Adds a try-catch-finally block&lt;/Description&gt;
    &lt;SnippetTypes&gt;
      &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
    &lt;/SnippetTypes&gt;
  &lt;/Header&gt;
  &lt;Snippet&gt;
    &lt;Declarations&gt;
      &lt;Literal&gt;
        &lt;ID&gt;ExceptionName&lt;/ID&gt;
        &lt;Default&gt;Exception&lt;/Default&gt;
      &lt;/Literal&gt;
    &lt;/Declarations&gt;
    &lt;Code Language=&quot;CSharp&quot;&gt;
      &lt;![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]&gt;
    &lt;/Code&gt;
  &lt;/Snippet&gt;
&lt;/CodeSnippet&gt;
</pre>
</pre>
<p><strong>Loading the Snippet into Visual Studio:</strong></p>
<p>There are two ways to insert the above snippet into Visual Studio. </p>
<p>The most straightforward way is to put the .snippet files in VS 2010&#8242;s code snippets directory. The default location for it is <font face="Courier New">C:\Users\&lt;UserName&gt;\Documents\Visual Studio 2010\Code Snippets\</font>. This folder contains sub-directories based on the language of the snippet. For my example, the snippet goes under Visual C#. Once put here, VS 2010 automatically picks up the snippets without the need to restart. </p>
<p>&#160;</p>
<p>The second option is to import the .snippet file into Visual Studio. </p>
<p>- Inside Visual studio, go to Tools-&gt;Code Snippets Manager (Ctrl+K,Ctrl+B). This brings up the Snippets Manager.<br />
  <br />- Press Import button, and navigate to the location where the snippet was saved. Select the .snippet file.</p>
<p>- Press OK.</p>
<p>&#160;</p>
<p><strong>Using the Code Snippet:</strong></p>
<p>Type the name of the snippet (the shortcut), and pressing tab expands it. </p>
<p><a href="http://umairsd.files.wordpress.com/2010/06/snippet1.png"><img src="http://umairsd.files.wordpress.com/2010/06/snippet1.png?w=500&h=516" alt="Intellisense after typing snippet name" title="Snippet1" width="500" height="516" class="alignnone size-full wp-image-122" /></a></p>
<p>You can also press Ctrl+K and Ctrl+X which brings up the &quot;Insert Snippet&quot; menu as shown below: </p>
<p><a href="http://umairsd.files.wordpress.com/2010/06/snippet2.png"><img src="http://umairsd.files.wordpress.com/2010/06/snippet2.png?w=500" alt="" title="Snippet2"   class="alignnone size-full wp-image-124" /></a></p>
<p>We can navigate to My Code Snippets, and select the TryCatchFinally that we&#8217;ve just added:</p>
<p><a href="http://umairsd.files.wordpress.com/2010/06/snippet3.png"><img src="http://umairsd.files.wordpress.com/2010/06/snippet3.png?w=500&h=190" alt="" title="Snippet3" width="500" height="190" class="alignnone size-full wp-image-125" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/118/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/118/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/118/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=118&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/06/22/code-snippets-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/06/snippet1.png" medium="image">
			<media:title type="html">Snippet1</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/06/snippet2.png" medium="image">
			<media:title type="html">Snippet2</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/06/snippet3.png" medium="image">
			<media:title type="html">Snippet3</media:title>
		</media:content>
	</item>
		<item>
		<title>XAML Resources</title>
		<link>http://umairsaeed.com/2010/05/05/xaml-resources/</link>
		<comments>http://umairsaeed.com/2010/05/05/xaml-resources/#comments</comments>
		<pubDate>Wed, 05 May 2010 13:53:56 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/2010/05/05/xaml-resources/</guid>
		<description><![CDATA[Every element in Silverlight contains a Resource property that maintains a dictionary of resources. This collection can hold any type, and a key is used to refer to each individual resource. Each element has access to its own resources as &#8230; <a href="http://umairsaeed.com/2010/05/05/xaml-resources/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=115&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Every element in Silverlight contains a Resource property that maintains a dictionary of resources. This collection can hold any type, and a key is used to refer to each individual resource. Each element has access to its own resources as well as the resources in all its parents. For this reason, a common way to define resources is at the page level so that all elements within that page can re-use that resource. If a given resource will be used across the entire application (i.e. multiple pages), then it is put in the &lt;Application.Resources&gt; section of the App.xaml file. </p>
<p>To find a resource, Silverlight recursively searches up the element tree terminating at the &lt;Application.Resources&gt; section in App.xaml file. </p>
<p>As an example, suppose I re-use a custom brush on multiple elements on my page. I put it in the &lt;UserControl.Resources&gt; section where it can be accessed by all elements on my page. It is defined as:</p>
<pre>
<pre class="brush: xml; auto-links: false;">
    &lt;UserControl.Resources&gt;
        &lt;LinearGradientBrush x:Key=&quot;CustomBrush&quot;&gt;
            &lt;GradientStop Offset=&quot;0.00&quot; Color=&quot;Yellow&quot; /&gt;
            &lt;GradientStop Offset=&quot;1.00&quot; Color=&quot;Orange&quot; /&gt;
        &lt;/LinearGradientBrush&gt;
    &lt;/UserControl.Resources&gt;
</pre>
</pre>
<p><strong>Using a Resource in XAML:</strong></p>
<p>Now that my CustomBrush has been defined, it can be re-used in XAML. A given element needs a way to refer to this resource in order to reuse it. This is accomplished by using a <a href="http://msdn.microsoft.com/en-us/library/ms752059.aspx#markup_extensions">markup extension</a>. Markup extensions are a specialized syntax to set a property in a non-standard way, and are recognized by curly braces. For example, let&#8217;s say the Grid element needs to use the CustomBrush defined above:</p>
<pre>
<pre class="brush: csharp;">
	&lt;Grid x:Name=&quot;outerGrid&quot; Background=&quot;{StaticResource BackgroundBrush}&quot;
</pre>
</pre>
<p>In this example, we use a markup extension named StaticResource. <a href="http://msdn.microsoft.com/en-us/library/ms750613.aspx#staticdynamic">Here&#8217;s</a> (MSDN<a href="http://msdn.microsoft.com/en-us/library/ms750613.aspx#staticdynamic)">)</a> some more information about static and dynamic resources</p>
<p><strong>Using a Resource in Code:</strong></p>
<p>In order to use CustomBrush in my code (e.g. C#), I can access the Resources property as a dictionary by using the key to index and retrieve the specific resource. </p>
<pre>
<pre class="brush: csharp;">
            Grid outerGrid = new Grid();
            LinearGradientBrush customBrush = 
                (LinearGradientBrush) this.Resources[&quot;CustomBrush&quot;];
            outerGrid.Background = customBrush;
</pre>
</pre>
<p>I can even update my resource in code. If I wanted to change the color gradient of my CustomBrush, I would do so as follows:</p>
<pre>
<pre class="brush: csharp;">
            LinearGradientBrush customBrush = 
                (LinearGradientBrush) this.Resources[&quot;CustomBrush&quot;];
            customBrush.GradientStops[0].Color = Colors.Brown;
            customBrush.GradientStops[1].Color = Colors.Red;
</pre>
</pre>
<p>The really nifty bit is that every element that uses this customBrush will automatically update to use the new colors. </p>
<p>Silverlight does not support dynamic resources (but WPF does), and as a result it is not possible to update the resource reference with a new object. For example, the following code is not allowed in Silverlight:</p>
<pre>
<pre class="brush: csharp;">
            this.Resources[&quot;CustomBrush&quot;] = new LinearGradientBrush();
</pre>
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/115/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=115&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/05/05/xaml-resources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
		<item>
		<title>Custom Attached Properties in Silverlight</title>
		<link>http://umairsaeed.com/2010/04/22/custom-attached-properties-in-silverlight/</link>
		<comments>http://umairsaeed.com/2010/04/22/custom-attached-properties-in-silverlight/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 15:02:35 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/04/22/custom-attached-properties-in-silverlight/</guid>
		<description><![CDATA[An attached property is a type of global property that is settable on any nested object. In Silverlight (and WPF), attached properties are usually defined as a specialized case of Dependency Properties, and like all dependency properties they are managed &#8230; <a href="http://umairsaeed.com/2010/04/22/custom-attached-properties-in-silverlight/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=112&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>An attached property is a type of global property that is settable on any nested object. In Silverlight (and WPF), attached properties are usually defined as a specialized case of Dependency Properties, and like all dependency properties they are managed by the Silverlight property system. Attached properties differ in that they do not have the conventional &quot;property wrapper&quot;. </p>
<p>Most commonly, attached properties are used in layout containers. Every control in XAML has its own set of internal properties. However, when this control is placed inside a container, it acquires additional features depending on the type of the container. For example, the Grid.Row property is created as an attached property because any control inside a Grid needs to specify the grid cell where it is positioned. For example:</p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;Grid x:Name=&quot;OuterGrid&quot;&gt;
	&lt;TextBox x:Name=&quot;innerBox&quot; Grid.Row=&quot;1&quot;/&gt;
&lt;/Grid&gt;
</pre>
</pre>
<p>Since the TextBox is nested inside the Grid, it gains the Row property which &quot;attaches&quot; to the TextBox instance. In essence, attached properties allow different child elements to specify values for a property defined in a parent element. Attached properties always use a two-part name of the form: AttachedPropertyProvider.PropertyName (OR simply DefiningType.PropertyName)</p>
<p>&#160;</p>
<p><strong>Defining a Custom Attached Property:</strong></p>
<p>Creating an attached property is similar to how we create a custom dependency property with a few subtle differences. Since I seem to love widgets so much, I will continue to use a custom WidgetControl as an example. In one of my <a href="http://umairsaeed.com/2010/04/16/dependency-properties/">previous posts</a> we saw how to create a custom dependency property for WidgetControl. In this post, we will see how to create the WidgetStateProperty as an attached property.</p>
<p>1. The first step is to define a static readonly DependencyProperty object that represents the property, and register this attached property with Silverlight. This is done via the Dependency.RegisterAttached() method.</p>
<pre>
<pre class="brush: csharp;">
        public static readonly DependencyProperty WidgetStateProperty =
            DependencyProperty.RegisterAttached(
                &quot;WidgetState&quot;,
                typeof(Boolean),
                typeof(WidgetControl),
                new PropertyMetadata(false));
</pre>
</pre>
<p>Notice that <a href="http://umairsaeed.com/2010/04/16/dependency-properties/">when we were creating custom dependency properties</a>, we used the DependencyProperty.Register() method. The parameters for both these methods are exactly the same: the property name (WidgetState in this example), the data type used by the property (bool), the type that owns this property (WidgetControl), and a PropertyMetadata object that provides additional information, such as default values. </p>
<p>2. Our attached property provider must also provide static GetXXX() and SetXXX() methods, where XXX is the name of our property (WidgetState). </p>
<pre>
<pre class="brush: csharp;">
        public static void SetWidgetState(UIElement element, Boolean value)
        {
            element.SetValue(WidgetControl.WidgetStateProperty, value);
        }

        public static Boolean GetWidgetState(UIElement element)
        {
            return (Boolean)element.GetValue(WidgetControl.WidgetStateProperty);
        }
</pre>
</pre>
<p>We now have a fully functioning attached property which can be set using the DefiningType.PropertyName syntax. The complete code for this WidgetControl is shown below:</p>
<pre>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Attached
{
    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty WidgetStateProperty =
            DependencyProperty.RegisterAttached(
                &quot;WidgetState&quot;,
                typeof(Boolean),
                typeof(WidgetControl),
                new PropertyMetadata(false));


        public static void SetWidgetState(UIElement element, Boolean value)
        {
            element.SetValue(WidgetControl.WidgetStateProperty, value);
        }

        public static Boolean GetWidgetState(UIElement element)
        {
            return (Boolean)element.GetValue(WidgetControl.WidgetStateProperty);
        }
    }
}

</pre>
</pre>
<p>Here&#8217;s a very simple example where we use WidgetControl and its WidgetState property. The code is in XAML: </p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;UserControl x:Class=&quot;Attached.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    xmlns:local=&quot;clr-namespace:Attached&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;local:WidgetControl&gt;
            &lt;TextBox x:Name=&quot;txtBox&quot; local:WidgetControl.WidgetState=&quot;true&quot;&gt;
            &lt;/TextBox&gt;
        &lt;/local:WidgetControl&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;

</pre>
</pre>
<p>Finally, a couple of good resources that talk more about dependecy and attached properties are <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx">here</a> [msdn.microsoft.com<a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx]&#8220;>]</a> and <a href="http://www.silverlightshow.net/items/Attached-Properties-in-Silverlight.aspx">here</a> [www.silverlightshow.net]</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/112/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=112&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/04/22/custom-attached-properties-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
		<item>
		<title>Resolution of Dependency Properties</title>
		<link>http://umairsaeed.com/2010/04/21/resolution-of-dependency-properties/</link>
		<comments>http://umairsaeed.com/2010/04/21/resolution-of-dependency-properties/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 22:51:21 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/04/21/resolution-of-dependency-properties/</guid>
		<description><![CDATA[As I mentioned in my previous blog post, dependency properties depend on any number of services (called property providers) for their values. The Silverlight runtime needs to follow strict rules of precedence to determine the value of a dependency property. &#8230; <a href="http://umairsaeed.com/2010/04/21/resolution-of-dependency-properties/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=111&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As I mentioned in my <a href="http://umairsaeed.com/2010/04/16/dependency-properties/">previous blog post</a>, dependency properties depend on any number of services (called property providers) for their values. The Silverlight runtime needs to follow strict rules of precedence to determine the value of a dependency property. This process is called dynamic value resolution. </p>
<p>Here&#8217;s a prioritized list of providers in their order of precedence: </p>
<p>1. <strong>Animation</strong>: If an animation is running and is changing the property value, Silverlight uses the animated value </p>
<p>2. <strong>Local Value</strong>: If the property value has been explicitly set through XAML or code (by using SetValue or the property wrapper), Silverlight uses the local value. </p>
<p>3. <strong>Templated Properties</strong>: Silverlight uses the template properties if the object has been built dynamically from templates (ControlTemplate or DataTemplate). </p>
<p>4. <a href="http://msdn.microsoft.com/en-us/library/system.windows.style.setters%28VS.95%29.aspx"><strong>Styles Setters</strong></a>: If the page or the application resource defines a Style that applies to the given element, with a Setter for its dependency property, then Silverlight assigns the value from the Setter to the dependency property.</p>
<p>5. <strong>Default Value</strong>: If no other property setter is at work, Silverlight assigns the default value to the dependency property. If a value is passed in through the <a href="http://msdn.microsoft.com/en-us/library/system.windows.propertymetadata.aspx">PropertyMetadata</a> object during dependency property registration, it will be used as the default value. If no value has been passed in, then the default value depends on the type (reference or value) used for storing that dependency property.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/111/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/111/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/111/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=111&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/04/21/resolution-of-dependency-properties/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
		<item>
		<title>Dependency Properties in Silverlight</title>
		<link>http://umairsaeed.com/2010/04/16/dependency-properties/</link>
		<comments>http://umairsaeed.com/2010/04/16/dependency-properties/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 12:59:42 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/04/16/dependency-properties/</guid>
		<description><![CDATA[Very simply, a property of an element that depends on a number of property-providers outside the element is called a &#34;dependency property&#34;. Each of these providers has its own level of precedence. These properties can be either set directly by &#8230; <a href="http://umairsaeed.com/2010/04/16/dependency-properties/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=96&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Very simply, a property of an element that depends on a number of property-providers outside the element is called a &quot;dependency property&quot;. Each of these providers has its own level of precedence. These properties can be either set directly by code, or by one of Silverlight&#8217;s services (i.e. property providers) such as animation, data binding, styles etc. </p>
<p>Dependency properties were originally introduced in WPF and are a key concept in both Silverlight and WPF. These dependency features are designed to be read and set in code just like normal properties. However, the internal implementation of dependency properties differs from the implementation of ordinary properties. </p>
<p>To better understand dependency properties, let&#8217;s consider an example (this example has been taken and modified from <a href="http://www.codeguru.com/csharp/.net/net_general/netframeworkclasses/article.php/c13449">this excellent blog post</a> ):</p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;UserControl x:Class=&quot;DependencyProperty.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;ItemsControl Foreground=&quot;Red&quot;&gt;
            &lt;TextBlock Foreground=&quot;Blue&quot;&gt;
                1st line of text
            &lt;/TextBlock&gt;
            &lt;TextBlock&gt;
                2nd line of text
            &lt;/TextBlock&gt;
        &lt;/ItemsControl&gt;

    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre>
</pre>
<p>In this example, we use two <font face="Courier New">TextBlock</font> controls to display two lines of text. The results of running this app are shown below:</p>
<p><a href="http://umairsd.files.wordpress.com/2010/04/figure-1.png"><img src="http://umairsd.files.wordpress.com/2010/04/figure-1.png?w=500" alt="Results of running the Silverlight app above" title="Figure-1"   class="alignnone size-full wp-image-99" /></a></p>
<p>The first <font face="Courier New">TextBlock</font> changes its Foreground property to Blue. Once we run this Silverlight app, we see that the first line of text has blue color, which matches our intuition since we did set the Foreground property to Blue. However, the second line of text is red. This is somewhat surprising (especially for folks who are new to WPF/Silverlight). I never set the Foreground property of the second <font face="Courier New">TextBlock</font> , so why is it red? </p>
<p>This is an example of dependency properties. Foreground of a <font face="Courier New">TextBlock</font> is a dependency property and the Silverlight runtime sets it to red, which is the value of the Foreground property of the encapsulating <font face="Courier New">ItemsControl</font> .</p>
<p><strong>Defining a Dependency Property</strong></p>
<p>The syntax for creating a dependency property is different than creating an ordinary .NET property. Let&#8217;s look at how to add a dependency property to a custom WidgetControl. </p>
<p>1. The first step is to define the object that represents the property. This is an instance of <a href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx">DependencyProperty</a> class. This object must be defined as static readonly field. By convention, this field has the name of the ordinary property plus the post-fix Property. For example, if my new property is called WidgetState, the DependencyProperty object will be called WidgetStateProperty. </p>
<pre>
<pre class="brush: csharp;">
         public static readonly DependencyProperty WidgetStateProperty;
</pre>
</pre>
<p>2. The second step is to register the dependency property with Silverlight. This step needs to be completed before any code uses the property, so it must be performed in a static constructor. </p>
<pre>
<pre class="brush: csharp;">
        static WidgetControl()
        {
            WidgetStateProperty = DependencyProperty.Register(
                &quot;WidgetState&quot;, 
                typeof(Boolean), 
                typeof(WidgetControl),
                new PropertyMetadata(false));
        }
</pre>
</pre>
<p>The arguments to DependencyProperty.Register() method are: the property name (WidgetState in this example), the data type used by the property (Boolean), the type that owns this property (WidgetControl), and a <a href="http://msdn.microsoft.com/en-us/library/system.windows.propertymetadata.aspx">PropertyMetadata</a> object that provides additional information. In this example, I am simply passing a default value of &quot;false&quot; to the PropertyMetadata constructor </p>
<p>3. Define a CLR wrapper property whose names matches the name of the dependency property. </p>
<pre>
<pre class="brush: csharp;">
        public Boolean WidgetState
        {
            get
            {
                return (Boolean)GetValue(WidgetStateProperty);
            }
            set
            {
                SetValue(WidgetStateProperty, value);
            }
        }
</pre>
</pre>
<p>We now have a fully functioning dependency property which can be set just like any other .NET property using the property wrapper </p>
<pre>
<pre class="brush: csharp;">
	widgetCtrl.WidgetState = True;
</pre>
</pre>
<p>OR, using XAML: </p>
<pre>
<pre class="brush: xml; auto-links: false;">
        &lt;cnmspc:WidgetControl x:Name=&quot;widgetCtrl&quot; WidgetState=&quot;True&quot;&gt;
        &lt;/cnmspc:WidgetControl&gt;
</pre>
</pre>
<p>The complete code for this WidgetControl is shown below: </p>
<pre>
<pre class="brush: csharp;">
    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty WidgetStateProperty;

        static WidgetControl()
        {
            WidgetStateProperty = DependencyProperty.Register(
                &quot;WidgetState&quot;, 
                typeof(Boolean), 
                typeof(WidgetControl),
                new PropertyMetadata(false));
        }

        public Boolean WidgetState
        {
            get
            {
                return (Boolean)GetValue(WidgetStateProperty);
            }
            set
            {
                SetValue(WidgetStateProperty, value);
            }
        }
    }
</pre>
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/96/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/96/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/96/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=96&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/04/16/dependency-properties/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/04/figure-1.png" medium="image">
			<media:title type="html">Figure-1</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a Custom XAML TypeConverter</title>
		<link>http://umairsaeed.com/2010/02/03/creating-a-custom-xaml-typeconverter/</link>
		<comments>http://umairsaeed.com/2010/02/03/creating-a-custom-xaml-typeconverter/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 14:47:29 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/02/03/creating-a-custom-xaml-typeconverter/</guid>
		<description><![CDATA[TypeConverters provide a means of converting a String to the appropriate .NET type or a new instance when XAML is processed. I&#8217;ve already looked at how the XAML parser searches for TypeConverters (XAML and TypeConverters ) Now let&#8217;s take a &#8230; <a href="http://umairsaeed.com/2010/02/03/creating-a-custom-xaml-typeconverter/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=90&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>TypeConverters provide a means of converting a String to the appropriate .NET type or a new instance when XAML is processed. I&#8217;ve already looked at how the XAML parser searches for TypeConverters (<a href="http://umairsaeed.com/2010/01/20/xaml-and-typeconverters-2/">XAML and TypeConverters</a> ) Now let&#8217;s take a look at how to create our custom TypeConverter. </p>
<p>At a minimum, for a class to conform to the Silverlight implementation of TypeConverters it must be a subclass of the TypeConverter class and must contain the following two members for converting from strings for XAML processing: </p>
<p>1. The class must override the <font face="Courier New"><a href="http://msdn.microsoft.com/en-us/library/y5th8ef6%28VS.96%29.aspx">CanConvertFrom(&#8230;)</a></font> method: </p>
<pre>
<pre class="brush: csharp;">
public virtual bool CanConvertFrom(
    ITypeDescriptorContext context,
    Type sourceType
)
</pre>
</pre>
<p>It must return true when the <font face="Courier New">sourceType</font> parameter is String, and otherwise defer to the base implementation. </p>
<p>2. The class must provide an implementation of <font face="Courier New"><a href="http://msdn.microsoft.com/en-us/library/zb260h9b%28VS.96%29.aspx">ConvertFrom(&#8230;)</a></font> method: </p>
<pre>
<pre class="brush: csharp;">
public virtual Object ConvertFrom(
    ITypeDescriptorContext context,
    CultureInfo culture,
    Object value
)
</pre>
</pre>
<p>To be usable as a TypeConverter implementation that supports XAML, this method must accept a string as the value parameter. If the string is valid, the returned object must support a cast to the type expected by the property. Otherwise it must return null. </p>
<p>The .NET specification for TypeConverters also contains two more key methods, which are <font face="Courier New">ConvertTo</font> and <font face="Courier New">CanConvertTo</font>. However, Silverlight 3 (as well as Silverlight 4 Beta) does not use <font face="Courier New">ConvertTo</font> and <font face="Courier New">CanConvertTo</font>, so you can skip these if your TypeConverter is for Silverlight&#8217;s XAML processing. It&#8217;s still a good idea to implement these two as a best practice for completing the wider interoperation functionality of the converter class. </p>
<p>&#160;</p>
<p><strong>Putting it all together: An Example:</strong></p>
<p>Suppose I have a custom Silverlight control called WidgetControl, that has a property called WidgetHeight. If you need to see how to add custom controls to your project, please check out my post &quot;<a href="http://umairsaeed.com/2010/01/27/adding-a-custom-silverlight-control/">Adding a Custom Silverlight Control</a>&quot;. I use this control in my XAML file as follows: </p>
<pre>
<pre class="brush: xml; auto-links: false;">
&lt;Custom:WidgetControl x:Name=&quot;widget&quot; WidgetHeight=&quot;2 inches&quot;/&gt;
</pre>
</pre>
<p>Somehow I need to handle the case where the unit of length is specified for the value of WidgetHeight property. This is done via a custom XAML TypeConverter called <font face="Courier New">CustomLengthConverter</font>, which is shown below: </p>
<pre>
<pre class="brush: csharp; wrap-lines: true;">
    public class CustomLengthConverter : TypeConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }


        public override object ConvertFrom(ITypeDescriptorContext
                context, CultureInfo culture, object value)
        {

            if (value == null)
            {
                return new Double();
            }
            if (value is string)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    return new Double();
                }

                string[] arguments = s.Split(' ');
                if (arguments.Length != 2)
                {
                    throw new ArgumentException(&quot;Value must have the format &lt;number length_unit&gt;&quot;);
                }
                else
                {
                    return InternalParseInput(arguments[0]);
                }
            }

            return base.ConvertFrom(context, culture, value);
        }


        public Double InternalParseInput(String inputString)
        {
            Double doubleValue;

            try
            {
                doubleValue = Double.Parse(inputString);
            }
            catch(Exception){
                doubleValue = new Double();
            }

            return doubleValue;
        }
    }
</pre>
</pre>
<p>Finally, in my WidgetControl class, I explicitly specify that the WidgetHeight property should use the CustomLengthConverter defined above: </p>
<pre>
<pre class="brush: csharp;">
    public partial class WidgetControl : UserControl
    {
	...

        [TypeConverter(typeof(CustomLengthConverter))]
        public Double WidgetHeight
        {
	   ...
        }
    }
</pre>
</pre>
<p>So every time my XAML for WidgetControl&#8217;s WidgetHeight property is parsed, the parser uses the <font face="Courier New">CustomLengthConverter</font> to convert the property value from String to the appropriate .NET type (Double)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/90/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=90&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/02/03/creating-a-custom-xaml-typeconverter/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding a Custom Silverlight Control</title>
		<link>http://umairsaeed.com/2010/01/27/adding-a-custom-silverlight-control/</link>
		<comments>http://umairsaeed.com/2010/01/27/adding-a-custom-silverlight-control/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 13:34:41 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/01/27/adding-a-custom-silverlight-control/</guid>
		<description><![CDATA[Silverlight has a ton of controls that we can use in our Silverlight apps. Most of the times, this collection of controls is sufficient, but every once in a while, we need to create a custom control. Adding a new &#8230; <a href="http://umairsaeed.com/2010/01/27/adding-a-custom-silverlight-control/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=81&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Silverlight has a ton of controls that we can use in our Silverlight apps. Most of the times, this collection of controls is sufficient, but every once in a while, we need to create a custom control. Adding a new custom control for Silverlight is fairly straightforward, and in this blog post I am going to take a look at the steps involved in adding a new control to our Visual Studio project.</p>
<p>(<strong>Note:</strong> My aim is to show the steps for adding a new control, so I will not go into the specifics of the control itself)</p>
<p>I am going to start by creating a new project (type: Silverlight Application) in Visual Studio. Let&#8217;s call it Widget. To add a new Custom control, right click on the project in Solution Explorer, and go to Add-&gt;New Item, as shown in the figure below:</p>
<p><a href="http://umairsd.files.wordpress.com/2010/01/03-addnewitem.png"><img class="alignnone size-full wp-image-82" title="03-AddNewItem" src="http://umairsd.files.wordpress.com/2010/01/03-addnewitem.png?w=500&h=375" alt="Add New Item" width="500" height="375" /></a></p>
<p>We get to a selection dialog which lists the various items that can be added. Let&#8217;s select &#8220;Silverlight User Control&#8221;, and change the name of the XAML file to <span style="font-family:Courier New;">WidgetControl.xaml</span></p>
<p><a href="http://umairsd.files.wordpress.com/2010/01/04-addnewitem_selection.png"><img class="alignnone size-full wp-image-84" title="04-AddNewItem_Selection" src="http://umairsd.files.wordpress.com/2010/01/04-addnewitem_selection.png?w=500&h=374" alt="Add New Item - Selection" width="500" height="374" /></a></p>
<p>For this example, my new control is a pretty basic control as it simply contains a TextBox. Open the <span style="font-family:Courier New;">WidgetControl.xaml</span> file, and add the TextBox element. Once done, the <span style="font-family:Courier New;">WidgetControl.xaml.cs</span> file looks like:</p>
<p><pre class="brush: xml; auto-links: false; highlight: [10];">
&lt;UserControl x:Class=&quot;Widget.WidgetControl&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;TextBox x:Name=&quot;txtBox&quot; Text=&quot;Widget Box&quot;&gt;&lt;/TextBox&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre></p>
<p>We can add new properties to our WidgetControl, and to illustrate this let&#8217;s add a new property called InternalText that is used to manipulate the text for the txtBox. Right click on the <span style="font-family:Courier New;">WidgetControl.xaml.cs</span> file, and click on &#8220;View class Designer&#8221;.</p>
<p><a href="http://umairsd.files.wordpress.com/2010/01/05-viewclassdiagram.png"><img class="alignnone size-full wp-image-85" title="05-ViewClassDiagram" src="http://umairsd.files.wordpress.com/2010/01/05-viewclassdiagram.png?w=500&h=378" alt="View Class Diagram" width="500" height="378" /></a></p>
<p>When the class designer opens up right click on the WidgetControl class, click Add-&gt;Property.</p>
<p><a href="http://umairsd.files.wordpress.com/2010/01/06-addproperty.png"><img class="alignnone size-full wp-image-86" title="06-AddProperty" src="http://umairsd.files.wordpress.com/2010/01/06-addproperty.png?w=500&h=377" alt="Add Property" width="500" height="377" /></a></p>
<p>Add the new String property called InternalText. Once the property has been added, the <span style="font-family:Courier New;">WidgetControl.xaml.cs</span> file will be updated automatically to include the new property. The file looks as follows:</p>
<p><pre class="brush: csharp; highlight: [22,23,24,25,26,27,28,29,30,31];">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Widget
{
    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public String InternalText
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }
    }
}
</pre></p>
<p>Since our new property simply wraps around the Text property of the TextBox, so let&#8217;s go ahead and implement our InternalText property:</p>
<p><pre class="brush: csharp;">
        public String InternalText
        {
            get
            {
                return txtBox.Text;
            }
            set
            {
                txtBox.Text = value;
            }
        }
</pre></p>
<p><strong>Using a Custom Control:</strong></p>
<p>Once we&#8217;ve created a custom control, using it is pretty straightforward. All we need is to declare our xml namespace, and start using the control. Continuing my example, I&#8217;ve added my custom WidgetControl to MainPage.xaml file. The code to make this happen is on lines 6 &amp; 11 below:</p>
<p><pre class="brush: xml; auto-links: false; highlight: [6,11];">
&lt;UserControl x:Class=&quot;Widget.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    xmlns:wts=&quot;clr-namespace:Widget&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
        &lt;wts:WidgetControl x:Name=&quot;widgetCtrl&quot; InternalText=&quot;Let's Text&quot;/&gt;
    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/81/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=81&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/01/27/adding-a-custom-silverlight-control/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/01/03-addnewitem.png" medium="image">
			<media:title type="html">03-AddNewItem</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/01/04-addnewitem_selection.png" medium="image">
			<media:title type="html">04-AddNewItem_Selection</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/01/05-viewclassdiagram.png" medium="image">
			<media:title type="html">05-ViewClassDiagram</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2010/01/06-addproperty.png" medium="image">
			<media:title type="html">06-AddProperty</media:title>
		</media:content>
	</item>
		<item>
		<title>XAML and TypeConverters</title>
		<link>http://umairsaeed.com/2010/01/20/xaml-and-typeconverters-2/</link>
		<comments>http://umairsaeed.com/2010/01/20/xaml-and-typeconverters-2/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 14:24:00 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/01/20/xaml-and-typeconverters-2/</guid>
		<description><![CDATA[In a XAML document, every element maps to an instance of a Silverlight (.NET) class. The properties of this instance can be set through attributes in the XAML file. There is a bit of a catch though. These attribute values &#8230; <a href="http://umairsaeed.com/2010/01/20/xaml-and-typeconverters-2/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=72&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In a XAML document, every element maps to an instance of a Silverlight (.NET) class. The properties of this instance can be set through attributes in the XAML file. There is a bit of a catch though. These attribute values (in the XAML file) are in text form, whereas the corresponding Silverlight property is a .NET type. There needs to be a way to convert these String attribute values into corresponding .NET types. This is where TypeConverters come in. </p>
<p>In the context of Silverlight, a TypeConverter is a class which knows how to convert between a String and a .NET type. For each attribute in XAML, the parser follows a two-step process to find the appropriate type converter: </p>
<p>1. The XAML parser checks the declaration of the property that corresponds to the XML attribute, and tries to see if the property contains a TypeConverter attribute. The TypeConverter attribute specifies the class that can perform the type conversion from String to the .NET type of the property. The parser then uses the TypeConverter class to convert the XML attribute into a .NET type. </p>
<p>2. If the property declaration does not contain a TypeConverter attribute, the XAML parser looks at the property&#8217;s Type, to see if it containts TypeConverter attribute declaration. </p>
<p>3. If neither the property declaration or type (class) declaration have an associated TypeConverter attribute, the XAML parser returns an error. </p>
<p>Let&#8217;s consider a couple of examples to better illustrate this. Suppose we have two .NET Types called a Widget and WidgetBox, which are defined as follows: </p>
<pre><pre class="brush: csharp; gutter: false;"> 
    public class Widget{
        public Brush Foreground
        {
        }
    }


    public class WidgetBox
    {
        [System.ComponentModel.TypeConverter(typeof(CustomLengthConverter)]
        public Double Height
        {
        }
    }

    public class CustomLengthConverter : System.ComponentModel.TypeConverter
    {
        ...
    }
</pre></pre>
<p><strong>Example-1:</strong> </p>
<p>Consider the following XML element in the XAML file. </p>
<pre><pre class="brush: xml; auto-links: false; gutter: false;">
	&lt;WidgetBox Height=&quot;1in&quot; /&gt;
</pre></pre>
<p>1. When the XAML parser encounters this code, it checks the property declaration for Height. In this case, it finds a TypeConverter attribute for the Height property, which tells the parser to use the CustomLengthConverter class to convert the string &quot;1in&quot; to Double. So, this snippet of XAML code is equivalent to: </p>
<pre><pre class="brush: csharp; gutter: false;"> 
	WidgetBox wb = new WidgetBox();
	wb.Height = new CustomLengthConverter().ConvertFrom(&quot;1in&quot;);
</pre></pre>
<p><strong>Example-2:<br />
    <br /></strong>Here&#8217;s another snippet of XAML code: </p>
<pre><pre class="brush: xml; auto-links: false; gutter: false;">
	&lt;Widget Foreground=&quot;Blue&quot; /&gt;
</pre></pre>
<p>1. When XAML parser encounters this code, it first checks the property declaration for Foreground. There&#8217;s no TypeConverter associated with the Foreground property, so the parser moves to step-2. </p>
<p>2. Now the XAML parser checks the class declaration of the Foreground&#8217;s Type. In our example, the type of Foreground is Brush, and it turns out that the Brush class is decorated with the [TypeConverter(typeof(BrushConverter))] attribute declaration: </p>
<pre><pre class="brush: csharp; gutter: false;"> 
	[TypeConverter(typeof(BrushConverter))]
	public class Brush
	{
	...
	}
</pre></pre>
<p>In this case, the parser uses the BrushConverter class to convert the string &quot;Blue&quot; into a Brush .NET type. So this snippet of XAML is equivalent to: </p>
<pre><pre class="brush: csharp; gutter: false;">  
	Widget w = new Widget();
	w.Foreground = new BrushConverter().ConvertFrom(&amp;quot;Blue&amp;quot;);
</pre></pre>
<p>For more information about TypeConverters, check out <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx">MSDN</a>. There&#8217;s also a lot of great information at <a href="http://blogs.windowsclient.net/rob_relyea/archive/2008/04/10/strings-to-things-or-how-xaml-interprets-attribute-values.aspx">Rob Relyea&#8217;s blog post</a> about TypeConverters</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/72/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=72&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/01/20/xaml-and-typeconverters-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
		<item>
		<title>Silverlight – Getting started with XAML</title>
		<link>http://umairsaeed.com/2010/01/17/silverlight-getting-started-with-xaml/</link>
		<comments>http://umairsaeed.com/2010/01/17/silverlight-getting-started-with-xaml/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 21:57:00 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2010/01/17/silverlight-getting-started-with-xaml/</guid>
		<description><![CDATA[XAML stands for eXtensible Application Markup Language (pronounced zamm-uhl). It is an XML based markup language used to instantiate .NET objects. XAML was initially designed as part of Windows Presentation Foundation (WPF), and allows developers to define rich user interfaces. &#8230; <a href="http://umairsaeed.com/2010/01/17/silverlight-getting-started-with-xaml/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=60&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>XAML stands for e<strong>X</strong>tensible <strong>A</strong>pplication <strong>M</strong>arkup <strong>L</strong>anguage (pronounced<em> zamm-uhl</em>). It is an XML based markup language used to instantiate .NET objects. XAML was initially designed as part of Windows Presentation Foundation (WPF), and allows developers to define rich user interfaces. A XAML file defines the elements that make up a content region. This enables a clean separation between UI and the business logic code. One big advantage of this separation is that the UI designers can focus on creating the user-interface in XAML (using tools such as <a href="http://www.microsoft.com/expression/">Microsoft&#8217;s Expression</a>), and the developers can then create the business objects corresponding to the UI.</p>
<p>XAML document has the following properties:</p>
<p>- Every element in a XAML documents maps to an instance of a Silverlight (.NET) class, and its name exactly matches that of the class.<br />
- The properties of each class can be set through attributes in the XAML file.<br />
- Similar to any XML document, a XAML element can contain nested elements.</p>
<p>For example, when we create a new Silverlight application (called SampleApplication) in Visual Studio 2010 (beta), we get the following skeleton XAML document:</p>
<p><pre class="brush: xml; auto-links: false;">
&lt;UserControl x:Class=&quot;SampleApplication.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&gt;

    &lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;

    &lt;/Grid&gt;
&lt;/UserControl&gt;
</pre></p>
<p>As I&#8217;ve mentioned before, XAML allows us to create user-interfaces. However, for the interface to be useful, it needs to connect to code (typically written in C#). To accomplish this, we need a way to connect the event handlers with the UI. Usually, every XAML file has a corresponding class with client-side C# code. This class is generated by the Class attribute in the XAML namespace. This attribute tells the Silverlight parser to create a new class with the specified name that derives from the class represented by the XML element. When the XAML code above is parsed, the parser creates a new class named <span style="font-family:Courier New;">SampleApplication.MainPage</span>, which derives from the <span style="font-family:Courier New;">UserControl</span> class. This class is in the file called <span style="font-family:Courier New;">MainPage.xaml.cs</span>:</p>
<p><pre class="brush: csharp; gutter: false;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SampleApplication
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

    }
}
</pre></p>
<p>The class is <a href="http://msdn.microsoft.com/en-us/library/wa80x488%28VS.80%29.aspx">partial</a> , as it is split across two files. The code that we write goes into <span style="font-family:Courier New;">MainPage.xaml.cs</span>. The rest of the class definition contains auto-generated code and goes into a file called <span style="font-family:Courier New;">MainPage.g.cs</span>. In the solution, this file is located in <span style="font-family:Courier New;">obj\Debug</span> folder. For the above XAML code, the contents of this auto-generated file are as follows:</p>
<p><pre class="brush: csharp; gutter: false;">
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace SampleApplication {

    public partial class MainPage : System.Windows.Controls.UserControl {

        internal System.Windows.Controls.Grid LayoutRoot;

        private bool _contentLoaded;

        /// &lt;summary&gt;
        /// InitializeComponent
        /// &lt;/summary&gt;
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri(&quot;/SampleApplication;component/MainPage.xaml&quot;, System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName(&quot;LayoutRoot&quot;)));
        }
    }
}
</pre></p>
<p>Finally, a quick note about the Name attribute. If we want to access and manipulate Silverlight elements programmatically, XAML must include the Name attribute. This is useful if we want to change properties or attach and detach event handlers on the fly. In the above example, line-9 of the XAML file tells the XAML parser to add the following field to the autogenerated portion of the <span style="font-family:Courier New;">MainPage</span> class</p>
<p><pre class="brush: csharp; gutter: false;">
private System.Windows.Controls.Grid LayoutRoot;
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/60/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&#038;blog=9333327&#038;post=60&#038;subd=umairsd&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2010/01/17/silverlight-getting-started-with-xaml/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
	</channel>
</rss>
