automatically generate wpf listview columns

this code generates automatically listview columns for all properties for the given datatype

public class BaseListView : ListView
{
  public BaseListView() {
    ItemsSourceProperty.AddOwner(typeof(BaseListView), new FrameworkPropertyMetadata(null, OnItemsSourcePropertyChanged));
  }

  private static void OnItemsSourcePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) {
    if (e.OldValue != e.NewValue && e.NewValue != null) {
      var lv = (BaseListView)dependencyObject;
      var gridView = new GridView();
      lv.View = gridView;
      gridView.AllowsColumnReorder = true;
      var properties = lv.DataType.GetProperties();
      foreach (var pi in properties) {
        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);
      }
    }
  }

  public Type DataType { get; set; }
}

here is the xaml usage

<Grid>
  <local:BaseListView x:Name="listView" DataType="{x:Type DummyType}" ItemsSource="{Binding Mode=OneWay, Path=DummyTypeList}" />
</Grid>

thats it

here is my answer at stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

Categories