如果简单地说,您的 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的视图模型和设置DataContext的内容:
public class MyViewModel
{
public List<String> Items
{
get { return new List<String> { "One", "Two", "Three" }; }
}
}
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>
ListBox.ItemTemplate
。默认行为只是打印它。 - pt12lol