c# - Windows Phone 上的绑定(bind)项目列表

标签 c# xaml data-binding windows-phone-8 windows-phone

我正在学习 Windows Phone 上的数据绑定(bind),到目前为止,我已经能够将单个对象绑定(bind)到应用程序的视觉端,但现在我试图了解如何根据数字创建视觉元素我在列表中拥有的对象

我有一个人的类(class)

public class Person
{
    public Person() { }
    public string name { get; set; } 
    public string fotoPath { get; set; }
}

我有一门用于收集人员的类(class)

public class PersonCollection
{
    public PersonCollection() { }
    public List<Person> personGroup { get; set; } 
}

然后我有我的页面代码,我在其中生成我的人员列表

    public partial class TestPage : PhoneApplicationPage
    {
      public TestPage()
      {
        InitializeComponent();
        Loaded += TestPage_Loaded;
      }

    void TestPage_Loaded(object sender, RoutedEventArgs e)
    {
        PersonCollection lista = new PersonCollection();
        lista.personGroup.Add(new Person(){name = "Mr.T", fotoPath = "/images/foto1.jpg"});
        lista.personGroup.Add(new Person(){name = "John", fotoPath = "/images/foto2.jpg"});

    }
}

在我的页面上,我想要一个网格,在每个单元格上显示我列表中每个人的照片和人员姓名(每行 2 人)。据我了解,我需要使用 DataTemplate,但目前我的努力失败了。 谁能给我一些指点吗?

最佳答案

以下是每行显示 2 个人的方法。首先,将源集合分成 2 组:

List<Tuple<Person, Person>> groupedItems = lista.personGroup
    .GroupBy(item => lista.personGroup.IndexOf(item) / 2)
    .Select(grp => new Tuple<Person, Person>(grp.First(), grp.Skip(1).FirstOrDefault()))
    .ToList();
items.ItemsSource = groupedItems;

现在使用在左列和右列中显示“Item1”和“Item2”的DataTemplate:

<ItemsControl x:Name="items"> 
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.Resources>
                    <DataTemplate x:Key="ColumnTemplate">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding name}" Width="150" />
                            <Image Source="{Binding fotoPath}" />
                        </StackPanel>
                    </DataTemplate>
                </Grid.Resources>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <ContentControl Content="{Binding Item1}" 
                                ContentTemplate="{StaticResource ColumnTemplate}" />
                <ContentControl Grid.Column="1" 
                                Content="{Binding Item2}" 
                                ContentTemplate="{StaticResource ColumnTemplate}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

关于c# - Windows Phone 上的绑定(bind)项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344451/

相关文章:

c# - 循环 TabItem 复选框

c# - ASP.NET 成员身份激活用户 - 用户 ID 作为查询字符串

wpf - 在 XAML 中的 ListView 内拉伸(stretch)网格

TableLayout 的 Android 数据绑定(bind)

c# - 如何将数据绑定(bind)到 HTML 选择框

c# - 为基于 Web 的应用程序实现功能齐全的原型(prototype)

c# - 互锁多变

c# - 如何更新 ToggleButton 内容的颜色?

xaml - ResourceLoader 在 ViewModel 中返​​回错误的语言

database - 结合 Hadoop MapReduce 和数据库查询