Silverlight中ListBox的数据绑定
在Silverlight中ListBox是一个非常强大的控件。总结下ListBox的绑定数据的方式。
首先,新建一个Book类,
1 public class Book 2 { 3 public string BookName { get; set; } 4 5 public string Author { get; set; } 6 }
接下来BookViewModel.cs中,
1 public class BookViewModel 2 { 3 private List<Book> booklist; 4 5 public BookViewModel() 6 { 7 this.booklist = new List<Book>() { 8 new Book(){BookName="book1",Author="author1"}, 9 new Book(){BookName="book2",Author="author2"}, 10 new Book(){BookName="book3",Author="author3"} 11 }; 12 } 13 14 public List<Book> BookList 15 { 16 get { return this.booklist; } 17 } 18 }
在View中,添加绑定ViewModel
1 <UserControl.DataContext> 2 <viewmodel:BookViewModel/> 3 </UserControl.DataContext>
有两种绑定ListBox的方式:
方式一:
1 <ListBox Name="listtmp" Grid.Row="1" Grid.Column="0" ItemsSource="{Binding BookList,Mode=TwoWay}" 2 DisplayMemberPath="BookName"/>
方式二:
1 <ListBox Grid.Row="1" Grid.Column="0" ItemsSource="{Binding BookList,Mode=TwoWay}"> 2 <ListBox.ItemTemplate> 3 <DataTemplate> 4 <StackPanel Orientation="Horizontal"> 5 <TextBlock Text="{Binding BookName,Mode=TwoWay}"/> 6 <TextBlock Text="||"/> 7 <TextBlock Text="{Binding Author,Mode=TwoWay}"/> 8 </StackPanel> 9 </DataTemplate> 10 </ListBox.ItemTemplate> 11 </ListBox>
以上。