WPF的ListBox和ListView有什么区别?我没有发现它们的性质有什么显著差异。有不同的典型用途吗?
ListView基本上类似于ListBox(并继承自它),但它也有View属性。此属性允许您指定一种预定义的显示项的方式。BCL (基类库)中唯一预定义的视图是GridView,但你可以很容易地创建自己的。
ListView
ListBox
View
GridView
另一个区别是默认选择模式:对于ListBox是Single,而对于ListView是Extended
Single
Extended
ListView允许你为它定义一组views,并提供了一种本地方法(WPF binding支持),通过使用已定义的views来控制ListView的显示。
views
WPF
binding
< em >例子:< / em >
< em > XAML < / em >
XAML
<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave"> <ListView.Resources> <GridView x:Key="one"> <GridViewColumn Header="ID" > <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding id}" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Name" > <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding name}" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> <GridView x:Key="two"> <GridViewColumn Header="Name" > <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding name}" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.Resources> <ListView.Style> <Style TargetType="ListView"> <Style.Triggers> <DataTrigger Binding="{Binding ViewType}" Value="1"> <Setter Property="View" Value="{StaticResource one}" /> </DataTrigger> </Style.Triggers> <Setter Property="View" Value="{StaticResource two}" /> </Style> </ListView.Style>
< em > Code Behind: < / em >
Code Behind:
private int viewType; public int ViewType { get { return viewType; } set { viewType = value; UpdateProperty("ViewType"); } } private void listv_MouseEnter(object sender, MouseEventArgs e) { ViewType = 1; } private void listv_MouseLeave(object sender, MouseEventArgs e) { ViewType = 2; }
输出:< em > < / em >
正常视图:上面XAML中的视图2
MouseOver View:上面XAML中的View 1
如果你试图在ListBox中实现上述目标,可能你最终会为ListBox的__abc1 /ItemTemplate编写更多的代码
ItemTemplate