A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
A ListView
let you define a set of views
for it and gives you a native way (WPF
binding
support) to control the display of ListView
by using defined views
.
Example:
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>
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;
}
OUTPUT:
Normal View: View 2 in above XAML
MouseOver View: View 1 in above XAML
If you try to achieve above in a
ListBox
, probably you'll end up writing a lot more code forControlTempalate
/ItemTemplate
ofListBox
.
Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With