Binding WPF DataGrid to DataTable using TemplateColumns

后端 未结 2 943
挽巷
挽巷 2020-11-29 09:32

I have tried everything and got nowhere so I\'m hoping someone can give me the aha moment. I simply cannot get the binding to pull the data in the datagrid successfully.

2条回答
  •  清歌不尽
    2020-11-29 10:28

    After finding this thread and having trouble with the code shown here, I ran across this thread on MSDN, and it works much better! No virtualization problems at all so far as I've seen.

    http://social.msdn.microsoft.com/Forums/en/wpf/thread/8b2e94b7-3c44-4642-8acc-851de5285062

    Code:

    private void dataGrid1_AutoGeneratingColumn(object sender, Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(MyData))
        {
            MyDataGridTemplateColumn col = new MyDataGridTemplateColumn();
            col.ColumnName = e.PropertyName;  // so it knows from which column to get MyData
            col.CellTemplate = (DataTemplate)FindResource("MyDataTemplate");
            e.Column = col;
            e.Column.Header = e.PropertyName;
        }
    }
    
    public class MyDataGridTemplateColumn : DataGridTemplateColumn
    {
        public string ColumnName
        {
            get;
            set;
        }
    
        protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            // The DataGridTemplateColumn uses ContentPresenter with your DataTemplate.
            ContentPresenter cp = (ContentPresenter)base.GenerateElement(cell, dataItem);
            // Reset the Binding to the specific column. The default binding is to the DataRowView.
            BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, new Binding(this.ColumnName));
            return cp;
        }
    }
    

提交回复
热议问题