Silverlight:在XAML中声明一组数据?

Nic*_*ner 5 c# silverlight xaml

我想在Silverlight for Windows Phone 7应用程序中声明一些数据.我不确定语法是什么.

例如:

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>
Run Code Online (Sandbox Code Playgroud)

显然Data不是有效的标签.我在这里想要什么?

Ant*_*nes 6

您首先需要定义容器类型: -

using System.Collections.ObjectModel;

...

public class People : ObservableCollection<Person> { }
Run Code Online (Sandbox Code Playgroud)

然后,您需要将您的People/Person类所存在的命名空间添加到Xaml typicall中,如下所示:

<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"
         >
Run Code Online (Sandbox Code Playgroud)

只需将"SilverlightApplication1"替换为您的应用程序命名空间即可.

现在你可以这样做: -

     <Application.Resources>
         <People x:Name="People">
             <Person Age="2" Name="Sam" />
             <Person Age="11" Name="Jane" />
         </People>
     </Application.Resources>
Run Code Online (Sandbox Code Playgroud)