gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:14 24 4
gpt4 key购买 nike

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

我有一个人的课

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;

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

<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com