Locations of visitors to this page

    Blog List       Minimize  
,NET:ASP:MVP
.NET
.NET 3.5
.NET:ACL
.NET:AppDomains
.NET:ASP
.NET:ASP ServerControls
.NET:ASP:Commerce
.NET:ASP:Config
.NET:ASP:JSON
.NET:ASP:Layout
.NET:ASP:Media/Flash
.NET:ASP:Mobile
.NET:ASP:Monitoring
.NET:ASP:MVC
.NET:ASP:Navigation
.NET:ASP:Stress Testing
.NET:ASP:Validation
.NET:ASP:WebParts
.NET:C#-Trig
.NET:CAB
.NET:CAS
.NET:Certification
.NET:CF
.NET:Collections
.NET:Configuration
.NET:Cryptography
.NET:Db
.NET:Delegates
.NET:Deployment
.NET:Diagnostics
.NET:Documentation
.NET:Encoding
.NET:Environment
.NET:Extension Methods
.NET:Globalization
.NET:I/O Streams
.NET:Interop
.NET:IO:Mail
.NET:IsolatedStorage
.NET:LicenseManager
.NET:LINQ
.NET:Metrics/Quality
.NET:Mono
.NET:MSOffice
.NET:Optimization
.NET:Patterns/Practices
.NET:Phone7
.NET:Reflection
.NET:Remoting
.NET:Reverse Engineering
.NET:Serialization
.NET:Silverlight
.NET:Silverlight UserGroup
.NET:Silverlight:Phone7
.NET:Threading
.NET:WCF
.NET:Windows Services
.NET:WinForms
.NET:WPF
.NET:Xml
Admin
Admin:Creating Software
Admin:CruiseControl
Admin:Estimating
Admin:Installers/Packaging
Admin:Methodologies
Admin:PM
Admin:SourceControl
Admin:UnitTesting
Admin:VisualStudio
Arch:Gen
Arch:Patterns
Arch:UML
Blogging
DB:Sqlite
DB:SqlServer
DB:SqlServer CE
DB:VistaDB
Graphs
IT
IT:DNN
IT:DOS
IT:IIS
IT:MailServers
IT:MS Office
IT:OS (XP/Vista/7)
Misc
Misc:Hardware
Misc:Humour
mISV:Accounting
mISV:Marketing
OS:Vista
Personal
Personal:Children
Personal:Faith
Personal:Family
Personal:History
Personal:Politics
Places:New Zealand
Places:Paris
Presentations
Tech:CSS
Tech:Regex
Tech:SQL
Tech:Web:HTML
Tech:XML/XSL
Web:HTML5

             
    Sprouting Synapses       Minimize  

             
Summary:

Binding to static resources is generally just an issue of following a simple recipe:

  • Ensure the relevant namespaces have been defined
  • Define an instance of the relevant type in the ResourceDictionary, and give it a x:key
  • Bind to it, using the {StaticResource} Markup Extension, and give it a Path= attribute if needed.

This post demonstrates how to do the following:

  • Binding to a static resource of simple String
  • Binding to a static resource of a single instance of a custom class
  • Binding to a static resource of a collection of custom instances
  • Binding to a static resource of a collection of strings



        Example: Binding to a static resource of simple String:
        Let’s start simply, just binding to a string defined as a static resource in a ResourceDictionary:

        <UserControl x:Class="SilverlightApplication10.UserControl4"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        
                     xmlns:sys="clr-namespace:System;assembly=mscorlib" 
        
                     Width="200" Height="250">
            
            <UserControl.Resources>
                <!-- A simple resource: just a string -->
                <sys:String x:Key="aSingleString">SkySigal</sys:String>
            </UserControl.Resources>
            
            <Grid>
              <!-- Binding to the resource's representation as a string -->
              <TextBlock Margin="0,0"
                         Text="{Binding Source={StaticResource aSingleString}}" />
              <!-- Binding to the resource's Path property -->
              <TextBlock  Margin="0,16"
                          Text="{Binding Source={StaticResource aSingleString}, Path=Length}"/>
            </Grid>
        </UserControl>

        Things to notice:

        • XAML doesn’t know about strings off the bat, so an xmlns has to be defined to point to the framework’s mscorelib assembly:
          xmlns:sys="clr-namespace:System;assembly=mscorlib"
        • Once the sys namespace has been defined, we could use it to define the static resource, tagged with an x:Key attribute:
          <sys:String x:Key="aSingleString">SkySigal</sys:String>
        • We refer back to this static resource with the {staticResource…} tag, pointing to the key of the resource:
          Text="{Binding Source={StaticResource aSingleString}}"
        • We can refer to a property of the static resource, using the Path attribute:
          Text="{Binding Source={StaticResource aSingleString}, Path=Length}"

         

         

         

        Example: Binding to a static resource of a single instance of a custom class:
        You’re not stuck with only using classes defined in the framework. For example, if you have defined a class Person:

        namespace SilverlightApplication10 {
        
          public class Person {
            public string FirstName { get; set; }
            public int Girth { get; set; }
          }
        }

        You just repeat the same recipe, first defining a namespace, declaring the instance, and then referring to the instance:

        <UserControl x:Class="SilverlightApplication10.UserControl11"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        
            xmlns:local="clr-namespace:SilverlightApplication10"
        
            Width="200" Height="200">
            
            <UserControl.Resources>
                <local:Person x:Key="aSinglePerson" FirstName="John"  Girth="104"/>
            </UserControl.Resources>
            
            <Canvas Background="White">
                <TextBlock 
                   Text="{Binding Source={StaticResource aSinglePerson}, Path=FirstName}"/>
            </Canvas>
            
        </UserControl>

        Notice how we did basically the same thing as in the last example:

        • First we ensure that we had a xml namespace pointing to the relevant C# namespace:
          xmlns:local="clr-namespace:SilverlightApplication10"
        • Then we instantiate a local resource using that xml namespace:
          <local:Person x:Key="aSinglePerson" FirstName="John" Girth="104"/>
        • Finally, we bind to the StaticResource:
          <TextBlock Text="{Binding Source={StaticResource aSinglePerson}, Path=FirstName}"/>

          If we had not used the Path= attribute, the returned value would have defaulted to the result of Person.ToString(), and would have looked like:
          SilverlightApplication10.Person

        Very Important:
        Note how the the Person property was for FirstName, and not just Name.
        Silverlight, and WPF, get confused if you refer to a class whose property is called Name, because it defaults to x:Name / Name.
        If you use Name, it won’t compile and just jams up. I don’t currently know of a way around this bug.

         

         

        Example: Binding to a static resource of a collection of custom instances:
        If we go back and define another class that the XAML can refer to, this time a collection of Person items, called Persons:

        namespace SilverlightApplication10 {
        
          // One person:
          public class Person {
            public string FirstName { get; set; }
            public int Girth { get; set; }
          }
        
          //A collection of persons:
          public class Persons : List<Person> {
            public Persons() {
              this.Add(new Person() { FirstName = "John", Girth = 60 });
              this.Add(new Person() { FirstName = "Betty", Girth = 30 });
            }
          }
        }

        we can update our XAML to instantiate and use it like this:

        <UserControl x:Class="SilverlightApplication10.UserControl4"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                     xmlns:sys="clr-namespace:System;assembly=mscorlib"
        
                     xmlns:local="clr-namespace:SilverlightApplication10"
        
                     Width="200" Height="250">
            
            <UserControl.Resources>
                <local:Person x:Key="aSinglePerson" FirstName="John" Girth="104"/>
                <local:Persons x:Key="somePersons"/>
            </UserControl.Resources>
            
            <Grid Background="White">
                <!-- Binding to the resource's FirstName property -->
                <TextBlock  Margin="0,32"
                          Text="{Binding Source={StaticResource aSinglePerson}, Path=FirstName}"/>
        
                <!-- Two ways of doing the same thing - binding to list as src for Items -->
                <ListBox  Margin="0,135,0,50" ItemsSource="{StaticResource somePersons}"/>
        
                <!-- But this allows you to specify look of item and what its bound to -->
                <ListBox  Margin="0,60,0,120" >
                    <ListBox.ItemsSource>
                        <Binding Source="{StaticResource somePersons}" />
                    </ListBox.ItemsSource>
        
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
        
                </ListBox>
        
            </Grid>
        </UserControl>

        The things to notice here are:

        • Once again, we start by importing a usable namespace:
          xmlns:local="clr-namespace:SilverlightApplication10"
        • Making a static resource:
          <local:Persons x:Key="somePersons"/>
        • Which we we use as the data source for the listbox:
          <ListBox Margin="0,135,0,50" ItemsSource="{StaticResource somePersons}"/>
        • But in this case, we defer the Path= definition to the actual binding, item by item:
          <ListBox.ItemTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Path=FirstName}"/>
           
           </DataTemplate>
          </ListBox.ItemTemplate>

         


        Example: Binding to a static resource of a collection of strings
        You may be wondering at this point how you can bind to a simple list of string…rather than having to go through all this extra work of defining a collection class, etc.

        In WPF you can use the x:Array tag (I wouldn’t at this time, as its unique to WPF), or you can import the System.Collections namespace in order to make a collection of Strings, like this:

        <UserControl x:Class="SilverlightApplication10.UserControl4"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                     xmlns:sys="clr-namespace:System;assembly=mscorlib"
                     xmlns:local="clr-namespace:SilverlightApplication10"
        
                     xmlns:sysCollections="clr-namespace:System.Collections;assembly=mscorlib"
                     Width="200" Height="250">
            
            <UserControl.Resources>
                
                <!-- An XAML defined collection of strings -->
                <sysCollections:ArrayList x:Key="justNames">
                    <sys:String>Tom</sys:String>
                    <sys:String>Baby</sys:String>
                    <sys:String>Mark</sys:String>
                    <sys:String>Fred</sys:String>
                </sysCollections:ArrayList>
                    
            </UserControl.Resources>
            
            <Grid Background="White">
        
              <!-- Binding to the list resource's Count property -->
              <TextBlock Margin="0,32"
                         Text="{Binding Source={StaticResource justNames}, Path=Count}" />
        
              <!-- Two ways of doing the same thing - binding to list as src for Items -->        
              <ListBox  Margin="0,60,0,120" >
                <ListBox.ItemsSource>
                  <Binding Source="{StaticResource justNames}" />
                </ListBox.ItemsSource>
              </ListBox>
                
              <ListBox  Margin="0,135,0,50" ItemsSource="{StaticResource justNames}"/>
        
            </Grid>
        </UserControl>

        Warning:
        But the above doesn’t work in Silverlight.
        Actually, to be completely clear about this -- while this will appear to work in the IDE (the UserControl will update as you type, and show the results of the Binding, etc.) it will throw an exception when you compile. The reason for the exception is that the Visual Studio IDE is using the full framework’s System.Collection.ArrayList class – but when it tries to compile the above XAML against the SL assemblies, it won’t find the ArrayList class as it has been deprecated by MS and is not part of the SL assemblies.

        In other words…it’s all a red herring.

        Is there any other solution? Yes.

        If you have the Silverlight Toolkit installed you can use the ObjectCollection inside of Microsoft.Windows.Controls like this:

        <UserControl x:Class="SilverlightApplication10.UserControl4" 
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
            xmlns:sys="clr-namespace:System;assembly=mscorlib" 
            xmlns:local="clr-namespace:SilverlightApplication10" 
            xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls" 
            Width="200" Height="250"> 
        
        
          <UserControl.Resources> 
            <controls:ObjectCollection x:Key="HardcodedStrings">
                <sys:String>Item 1</sys:String>
                <sys:String>Item 2</sys:String>
                <sys:String>Item 3</sys:String>
            </controls:ObjectCollection>
          </UserControl.Resources>
        ...
        </UserControl>

        Although you should seriously consider if you need to include Microsoft.Windows.Controls if that’s all you need from it (it is 196K after all), when the class, as first described here, is only:

        public partial class ObjectCollection : Collection<object> {
        
        #region Constructors
               public ObjectCollection() {
               }
        
               public ObjectCollection(IEnumerable collection){
                   foreach (object obj in collection) {
                       Add(obj);
                   }
               }
        #endregion
        
        }//Class:End

        In other words, all you have to do is define in your assembly the above class, and use something like the following:

        <UserControl x:Class="SilverlightApplication10.UserControl4"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                     xmlns:sys="clr-namespace:System;assembly=mscorlib"
        
                     xmlns:local="clr-namespace:SilverlightApplication10"
        
                     Width="200" Height="250">
            
            <UserControl.Resources>
                <local:ObjectCollection x:Key="HardcodedStrings">
                    <sys:String>Item 1</sys:String>
                    <sys:String>Item 2</sys:String>
                    <sys:String>Item 3</sys:String>
                </local:ObjectCollection>
            </UserControl.Resources>
            
            <Grid Background="White">
                <!-- Two ways of doing the same thing - binding to list as src for Items -->
                <ListBox  Margin="0,135,0,50" ItemsSource="{StaticResource HardcodedStrings}"/>
        
                <!-- But this allows you to specify look of item and what its bound to -->
                <ListBox  Margin="0,60,0,120" >
                    <ListBox.ItemsSource>
                        <Binding Source="{StaticResource HardcodedStrings}" />
                    </ListBox.ItemsSource>
        
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=.}"></TextBlock>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
        
                </ListBox>
        
            </Grid>
        </UserControl>

         

        Edit – An possible improvement: a TypedObjectCollection
        If you are interested in how to Type check such collection, check out this post (Silverlight- Using a Typed ObjectCollection).

         

        StaticResource versus DynamicResource
        Note that if you are coming from WPF, you need to know that SL 2.0 does not support the {DynamicResource…} Markup Extension

        If you don’t know what a DynamicResource is, this is a simple introduction to it (and read the first comment).

        BookMark: Trackback

        What now?!?

        You've got to the end of the post...now what?

        Well...a Comment would be nice... It doesn't have to be long...Will just a take a sec...

        Thanks!

        And (in a perfect world) if I was able to save you some time on your project:

        10 comment(s) so far...

        Re: Silverlight: DataBinding to a static resource

        Thanks!

        This was very helpful.

        By Daniel Lehmann on   9/24/2009 2:29 AM

        Re: Silverlight: DataBinding to a static resource

        Very nice post.Thanks for sharing.

        By Klinger on   1/21/2010 8:28 AM

        Re: Silverlight: DataBinding to a static resource

        Nice post, I've seen a similar article somewhere but Yours has more detail ... :)

        By Adriaan Davel on   1/21/2010 8:36 AM

        Re: Silverlight: DataBinding to a static resource

        Thanks. Your comment started my morning on a good foot :-)

        I'm generally way too lazy to micromanage this site to the level required to keep it focused (I already have enough of a hard time finding the time to feed the Silverlight FAQ)...but this morning I had a sec, and finally deleted the parts of the thread involving that jerk's comments, and get this page back on track.

        Sorry for the necessary collateral editing/tweaking.

        The *other* reason that I'm in a good mood this morning is that I just picked up another Silverlight project to do...The market is slowly unfolding its petals...yeah!

        By Sky on   1/21/2010 8:35 AM

        Re: Silverlight: DataBinding to a static resource

        Article Sweetheart et commentaires.

        By <a href="http://www.jouercasino.eu"&g on   1/25/2010 12:30 AM

        fwclfuay

        fwclfuay
        # fwclfuay

        By TrackBack on   4/19/2010 9:39 PM

        so beautiful shoes for you

        Welcome to our online shoes store www.christianlouboutinshoesstore.com
        We
        will introduce you to
        christian louboutin shoes
        .
        Louboutin spent the early years of his career designing for some of fashion's biggest names, including Chanel. In 1992
        christian louboutin opened up his own shop at the end of a picturesque 19th century Parisian arcade. He still runs his business from that Rue Jean-Jacques Rousseau address, but now his
        louboutin shoesare sold in 46 countries around the world. He has 14 boutiques in cities such as New York, Los Angeles, Las Vegas and London, and he plans to open six more next year in places like Singapore, Jakarta and Beijing. He counts Oprah, Sarah Jessica Parker, Cameron Diaz, Katie Holmes and hundreds of other Hollywood stars among his loyal clientele.We hope you also our loyal clientele,thank you!!

        By louboutin on   5/27/2010 1:33 PM

        <a href="http://www.coachoutletmalls.com/">Coach outlet</a> <a href="http://www.coachoutletmalls.com/">coach bags outlet</a> <a href="http://www.coachoutletmalls.com/">coach outlet store</a&

        Coach outlet
        coach bags outlet
        coach outlet store
        coach outlet online
        gucci handbags outlet
        gucci outlet
        gucci handbags
        gucci handbags
        gucci handbags outlet
        gucci outlet
        This article is written by zocy004 on 2010-7-15 www.coachoutletmalls.com

        By coach outlet on   7/15/2010 6:34 PM

        <a href="http://www.mbtshoesaleonline.com">mbt outlet</a> <a href="http://www.mbtshoesaleonline.com">mbt shoes</a> <a href="http://www.mbtshoesaleonline.com">mbt shoes on sale</a> <a hre

        mbt outlet
        mbt shoes
        mbt shoes on sale
        coach handbags
        coach handbags outlet
        coach bags on sale
        coach outlet
        This article is written by zocy004 on 2010-7-29 www.coach-handbags-outlet.com

        By coach outlet on   7/29/2010 6:18 PM

        <a href="http://www.my-ugg.com">cheap uggs</a> <a href="http://www.puma-shoes-outlet.com">puma outlet</a> <a href="http://www.lv-outlets.com">louis vuitton</a> <a href="http://www.n

        cheap uggs
        puma outlet
        louis vuitton
        discount basketball shoes
        air force 1
        ed hardy on sale
        nike outlet
        ugg sale
        basketball shoes
        burberry
        louis vuitton outlet
        ed hardy
        pumps shoes
        nike shoes
        armani
        ugg boot
        armani outlet
        nike air force
        Burberry outlet
        ugg boots
        pumps outlet
        puma shoes

        By tian471ian on   7/29/2010 8:46 PM

        Your name:
        Your email:
        (Optional) Email used only to show Gravatar.
        Your website:
        Title:
        Comment:
        Security Code
        Enter the code shown above in the box below
        Add Comment   Cancel 
        Copyright 2007 by Sky Sigal