Generate WPF ListView columns automatically
Sometimes it’s not necessary to display a list of elements with a DataGrid
, for a simple short way we can use the lighter ListView
. My solution, also posted at stackoverflow, generates a ListView
with columns for all properties with a given datatype automatically.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class BaseListView : ListView
{
public Type DataType { get; set; }
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property.Name == "ItemsSource"
&& e.OldValue != e.NewValue
&& e.NewValue != null
&& this.DataType != null)
{
CreateColumns(this);
}
}
private static void CreateColumns(BaseListView lv)
{
var gridView = new GridView { AllowsColumnReorder = true };
var properties = lv.DataType.GetProperties();
foreach (var pi in properties)
{
var browsableAttribute = pi.GetCustomAttributes(true).FirstOrDefault(a => a is BrowsableAttribute) as BrowsableAttribute;
if (browsableAttribute != null && !browsableAttribute.Browsable)
{
continue;
}
var binding = new Binding { Path = new PropertyPath(pi.Name), Mode = BindingMode.OneWay };
var gridViewColumn = new GridViewColumn() { Header = pi.Name, DisplayMemberBinding = binding };
gridView.Columns.Add(gridViewColumn);
}
lv.View = gridView;
}
}
1
2
3
4
5
<Grid>
<local:BaseListView x:Name="listView"
DataType="{x:Type DummyType}"
ItemsSource="{Binding Mode=OneWay, Path=DummyTypeList}" />
</Grid>
That’s it.
This post is licensed under CC BY 4.0 by the author.