请参阅类的名称。如果简单地把你的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" }; }
}
}
//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>
希望这有助于!:)
谢谢,我很困惑YourListBox。它是控制的名称吗?你是否必须在代码中使用xaml工作的第一行? – 2012-02-22 09:07:12
这是一个错字,它确实是控件的名称。您还可以通过页面上的DataContext或通过资源来绑定项目。我给的绑定是为了演示目的。 :) – Abbas 2012-02-22 09:09:47
谢谢,你能给我一个DataContext的例子吗?我很难理解它。 – 2012-02-22 09:13:43