栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在WPF / WP7中将数据列表绑定到ListBox?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在WPF / WP7中将数据列表绑定到ListBox?

如果简单地说,您的ItemsSource是这样绑定的:

YourListBox.ItemsSource = new List<String> { "One", "Two", "Three" };

您的XAML应该如下所示:

<ListBox Margin="20" Name="YourListBox">    <ListBox.ItemTemplate>         <DataTemplate>  <StackPanel Orientation="Horizontal">      <TextBlock Text="{Binding}" />  </StackPanel>         </DataTemplate>     </ListBox.ItemTemplate> </ListBox>

更新:

这是使用DataContext时的解决方案。以下代码是您将传递给页面的DataContext的ViewModel和DataContext的设置:

public class MyViewModel{    public List<String> Items    {        get { return new List<String> { "One", "Two", "Three" }; }    }}//This can be done in the Loaded event of the page:DataContext = new MyViewModel();

您的XAML现在看起来像这样:

<ListBox Margin="20" ItemsSource="{Binding Items}">    <ListBox.ItemTemplate>        <DataTemplate> <StackPanel Orientation="Horizontal">     <TextBlock Text="{Binding}" /> </StackPanel>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>

这种方法的优点是,您可以在MyViewModel类中放置更多的属性或复杂的对象,并将其提取到XAML中。例如,传递一个Person对象列表:

public class ViewModel{    public List<Person> Items    {        get        { return new List<Person> {     new Person { Name = "P1", Age = 1 },     new Person { Name = "P2", Age = 2 } };        }    }}public class Person{    public string Name { get; set; }    public int Age { get; set; }}

和XAML:

<ListBox Margin="20" ItemsSource="{Binding Items}">    <ListBox.ItemTemplate>        <DataTemplate> <StackPanel Orientation="Horizontal">     <TextBlock Text="{Binding Path=Name}" />     <TextBlock Text="{Binding Path=Age}" /> </StackPanel>        </DataTemplate>    </ListBox.ItemTemplate></ListBox>

希望这可以帮助!:)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465288.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号