将DataTable作为ListView数据源
无废话,看代码:
public MainWindow()
{
InitializeComponent();
GridView view = new GridView();
lvw1.View = view;
lvw1.ItemsSource = _table.DefaultView;
GridViewColumn col = new GridViewColumn();
col.Header = "姓名";
col.Width = 150;
col.CellTemplate = CreateLabel("Name");
view.Columns.Add(col);
col = new GridViewColumn();
col.Header = "性别";
col.Width = 150;
col.CellTemplate = CreateLabel("Gender");
view.Columns.Add(col);
_table.Columns.Add("Name", typeof(string));
_table.Columns.Add("Gender", typeof(string));
}
private DataTable _table = new DataTable();
private void AddDataButton_Click(object sender, RoutedEventArgs e)
{
_table.Rows.Add("张三", "南");
}
private DataTemplate CreateLabel(string prop)
{
DataTemplate ret = new DataTemplate() { DataType = typeof(TextBlock) };
FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));
Binding binding = new Binding();
binding.Path = new PropertyPath(prop);
fef.SetBinding(TextBlock.TextProperty, binding);
fef.SetValue(Control.ForegroundProperty, new SolidColorBrush(Colors.Red));
ret.VisualTree = fef;
return ret;
}