A discussion about Rich Internet Applications, and user experience focusing on architecture, design patterns and methodologies.

Saturday, April 17, 2010

Dictionarys in XAML

Short and simple post about how to declare and bind to a custom dictionary in Silverlight 4.  I had trouble finding a solid example of this since it has been properly introduced in the full release of Silverlight this past week.

Essentially I derived from Dictionary<String,String> and called it CustomDictionary within the application project.  Add a namespace declaration called local for the project and then:

<UserControl.Resources>
<local:CustomDictionary x:Name="dictionary">
<
sys:String x:Key="One">1</sys:String>
<
sys:String x:Key="Two">2</sys:String>
<
sys:String x:Key="Three">3</sys:String>
</
local:CustomDictionary >
</
UserControl.Resources>

<
Grid>
<
TextBlock Text="{Binding Source={StaticResource dictionary}, Path=[One]}"></TextBlock>
</Grid>



Quite simple really.  You bind to the dictionary resource and specify the key as the path.



Why do this?  I really like the idea of creating a dynamic and blendable ViewModel locator (thanks John Papa http://bit.ly/b11pUB) and I wanted to try my hand at doing this myself without the converter.



I’m planning on posting a blog on using MEF for composition and DI soon.  I think for smaller projects, it makes sense to keep it simple.  For larger projects, Unity might make more sense.

No comments:

About Me

My photo
Toronto, ON, Canada
I am a technical architect at Navantis, with over 12 years experience in IT. I have been involved in various projects, including a Hospital information system called CCIS for which my team received the 2007 Tech-Net innovation award. I have been working with Silverlight since beta 1, and am very keen on practically applying this technology and WPF to line of business applications.