如果简单地说,您的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>希望这可以帮助!:)



