[英]data binding to grid with unknown number of columns
如何綁定到列數未知的WPF網格?
我有一個可以返回列數和列名等的類,以及將綁定到每一行的項目。 基本上,我想做不使用數據表的數據表可以做的事情。 必須有一個我需要實現的接口或類似的東西。
如果您的對象(DataContext)實現IEnumerable,則datagrid將能夠吸收對象並顯示記錄。 只需將AutoGenerateColumns設置為true,它將根據您傳遞的對象為您生成列。
我最終通過使用SyncFusion網格控件解決了這個問題。 我發現內置網格以及市場上幾乎所有的網格都非常朝向一行,即從數據庫返回的對象。
如果您偏離此模型,則大多數網格將變得無用或至少很難使用。 在我的情況下,數據庫中的每一行都代表一個單元格。 我對所有網格都存在的關鍵問題是獲取WPF模板來處理未綁定的數據。 SyncFusion網格是我發現的唯一可以與這兩個功能( ubound
數據和數據模板)一起使用的網格。
我還發現flexgrid將解決此問題,盡管在這方面使用它有點困難。
最好的解決方案是使用Anonymous Types
。 它運行完美,請參閱以下概念證明:
<Window x:Class="AnonymousTypes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
<Grid>
<DataGrid Name="MyDataGrid" ItemsSource="{Binding}" AutoGeneratedColumns="OnMyDataGridAutoGeneratedColumns">
</DataGrid>
</Grid>
</Window>
后面的代碼:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
namespace AnonymousTypes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class Employee
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public int Job { get; set; }
public string Address { get; set; }
}
private ObservableCollection<Employee> _empCollection;
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Id = 234, Code = "E041", Name = "Employee1", Job = 1, Address = "..."},
new Employee {Id = 245, Code = "E701", Name = "Employee2", Job = 3, Address = "..."},
new Employee {Id = 728, Code = "E001", Name = "Employee3", Job = 9, Address = "..."},
new Employee {Id = 663, Code = "E051", Name = "Employee4", Job = 7, Address = "..."},
};
// Notice that here you can chose the column you want,
// and it can be variable with each query depending on your needs
// Just add the columns you need to the anonymous type
DataContext =
(from i in _empCollection
select new {TheCode = i.Code, TheName = i.Name, TheAddress = i.Address }).ToList();
}
private void OnMyDataGridAutoGeneratedColumns(object sender, EventArgs e)
{
// Now you can change the column names as you need
MyDataGrid.Columns[0].Header = "Header 1 [Code]";
MyDataGrid.Columns[1].Header = "Header 2 [Name]";
MyDataGrid.Columns[2].Header = "Header 3 [Address]";
}
}
}
您可以在數據綁定完成后使用AutoGeneratedColumns
事件更改列標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.