您的位置:首页 > 其它

将DataTable作为ListView数据源

2016-05-07 16:30 309 查看

将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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: