c# - 具有任意列和行的 Wpf DataGrid 数据绑定(bind)

标签 c# wpf xaml binding datagrid

对于我的一个项目,我尝试从文件(例如 *.csv)加载数据并将其显示在 DataGrid 中。文件的格式没有给出。例如,列数和行数因文件而异。因此,任务是将通用数据表加载到程序中,并在 DataGrid 中查看它。

我的第一次尝试是使用 DataTable 并将其以某种方式绑定(bind)到 DataGrid。然而,经过一段时间的搜索,我了解到使用 DataTable 并不是最好的解决方案,应该改用数据模型。不幸的是,网络中的大多数示例都使用具有固定数据列的数据。此外,我无法使 DataGridDataTable 之间的绑定(bind)正常工作。如果能够对两端的数据进行更改,那就太好了:DataGrid(如用户所愿)和底层数据结构(如代码所愿)。

有人能解释一下,为什么不应该使用 DataTable 吗?应该使用什么来实现上述行为?

数据加载本身应该不是问题,但是如何灵活地存储、处理和绑定(bind)数据表到DataGrid才是问题。

以下代码可以正常工作。然而,它似乎不响应对数据的任何更改,如添加行或列,但 DataTable 包含正确的数据。

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True"
 x:Name="myDataGrid1" AutoGenerateColumns="True" ItemsSource="{Binding myDataTable}"  />
DataTable myDataTable  { get; private set; }
...
myDataGrid.DataContext = this;
LoadData();
myDataGrid.ItemsSource = myDataTable.DefaultView;

非常感谢任何帮助!提前致谢!

最佳答案

尝试将 ItemsSource 设置为 BindingListCollectionView .到目前为止,我一直很幸运。我使用这些扩展方法:

  public static BindingListCollectionView GetCollectionView(this DataTable table)
        {
            return new BindingListCollectionView(table.DefaultView);
        }



 public static DataTable GetDataTable(this BindingListCollectionView view)
    {
        var dataView = view.SourceCollection as DataView;
        if (dataView != null)
        {
            return dataView.Table;
        }

        return null;
    }

在您的代码中使用它,例如:

myDataGrid.ItemsSource = myDataTable.GetCollectionView();

var view = myDataGrid.ItemsSource as BindingListCollectionView;
var table = view.GetDataTable();

您应该能够像往常一样使用 DataTable 对象,并保留网格所做的所有更改。

关于c# - 具有任意列和行的 Wpf DataGrid 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938032/

相关文章:

WPF MVVM 获取文本框数据到 ViewModel

c# - 通过 dbus-sharp 访问 NetworkManager 连接设置

c# - 如何在文本区设置空值

c# - 如何使用数据库优先方法命名外键

c# - Azure Blob 存储异常 "An existing connection was forcibly closed by the remote host"

c# - Word 加载项拖放到文档中

c# - Prism:如何从内存中删除现有的 View 实例

c# - 使用 Xamarin.Forms 中的 View 模型属性绑定(bind)到 StaticResource?

c# - 基于SelectedItem设置ComboBox的IsEnabled属性

WPF - GridSplitter 在两个网格之间不起作用