WP8中的网格数据源

时间:2013-09-14 13:06:06

标签: c# wpf windows-phone-8

我对WP8真的很陌生......我仍然要理解我在aspnet开发时常常面对的一些机制...例如,数据源,数据绑定,......

我不明白如何可视化网格中的某些元素:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Loaded="ContentPanel_Loaded">

      <TextBlock x:Name="xx" .../>  
</Grid>

我只想重复文本块n次......在这一刻,我设法做到这一点的唯一方法就是像这样做这样的

foreach (....)
{
     TextBlock tb = new TextBlock();
     tb.Text = p.Name;

     ContentPanel.Children.Add(tb);
}

但我认为这不是正确的方法......任何建议?感谢名单

1 个答案:

答案 0 :(得分:1)

这是xaml

<ListBox x:Name="NameList">
   <ListBox.ItemTemplate>
        <DataTemplate>
           <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding Path=Name}" Width="200"/>

           </StackPanel>
         </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

CS

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StackOverFlowTestApp.Resources;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.UserData;

namespace StackOverFlowTestApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        private SaveAppointmentTask saveAppointmentTask;
        private List<int> listMinutes = new List<int>();
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            List<User> list = new List<User>();
            for (int i = 0; i < 10; i++) {
                User user = new User();
                user.name = "Anobik"+i;
                list.Add(user);
            }
            NameList.ItemsSource = list;
        }


    }


    public class User {
        public string name { get; set; }
    }


}

尝试最简单的方法。但实际上绑定的概念扩展到MVVM,所以你可以阅读文章

MVVM windows phone 8