更好的方法是将 ItemsSource 绑定到数据模型 Car 类型的新类的 ObservableCollection
你的看法
.xaml
<StackPanel>
<ListBox ItemsSource="{Binding DataCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text=" - "/>
<TextBlock Text="{Binding Id}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
你的模型
Car.cs
public class Car
{
public string Name { get; set; }
public int Id { get; set; }
}
您的视图模型将有一个 Collection 将绑定到 ItemsSource
CarViewModel.cs
public ObservableCollection<Car> DataCollection { get; set; }
DataCollection = new ObservableCollection<Car>
{
new Car { Name = "VW Golf GTI", Id = 30000 },
new Car { Name = "Porsche GT3", Id = 30000 },
new Car { Name = "Porsche Cayenne", Id = 80000 },
new Car { Name = "BMW M6", Id = 90000 }
};