Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: Declaring a collection of data in XAML?

I would like to declare some data in my Silverlight for Windows Phone 7 application. I'm not sure what the syntax is.

For example:

public class Person 
{
      public string Name {get; set;}
      public int Age {get; set;}
}

<Application.Resources>
    <Data x:Name="People">
         <Person Age="2" Name="Sam" />
         <!-- ... -->
    </Data>
</Application.Resources>

Obviously Data is not a valid tag. What do I want here?

like image 962
Nick Heiner Avatar asked Jan 04 '11 22:01

Nick Heiner


1 Answers

You will need to define a container type first of all:-

using System.Collections.ObjectModel;

...

public class People : ObservableCollection<Person> { }

You then need to add the namespace that your People/Person classes are present in to the Xaml typicall this would look like:-

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:SilverlightApplication1"
         x:Class="SilverlightApplication1.App"
         >

Just replace "SilverlightApplication1" with your application namespace.

Now you can do:-

     <Application.Resources>
         <People x:Name="People">
             <Person Age="2" Name="Sam" />
             <Person Age="11" Name="Jane" />
         </People>
     </Application.Resources>
like image 163
AnthonyWJones Avatar answered Nov 07 '22 03:11

AnthonyWJones