简体   繁体   English

WPF DataGrid自定义模板自动生成的列内容绑定

[英]WPF DataGrid Custom Template auto generated column content binding

so I've got a datagrid whose SourceItem structure is unknown, but needs a tiny tweak... i'm using AutoGenerateColumns but for one of the data types I override with my own column using the dg_AutoGeneratingColumn event wherein I check the e.PropertyType and override the e.Column with my new ColumnTemplate (inherits from DataGridBoundColumn). 所以我有一个Datagrid,它的SourceItem结构是未知的,但是需要细微调整...我正在使用AutoGenerateColumns,但是对于其中一种数据类型,我使用dg_AutoGeneratingColumn事件用自己的列覆盖了其中,我检查了e.PropertyType并使用我的新ColumnTemplate覆盖e.Column(继承自DataGridBoundColumn)。

Generally speaking it executes and renders fine, except that i'm trying to get the data binding (path is unknown) to flow into my custom ColumnTemplate. 一般来说,它可以执行并呈现良好的效果,除了我试图使数据绑定(路径未知)流入我的自定义ColumnTemplate中。

CustomTemplate : DataGridBoundColumn
{
    public static DependencyProperty dpblah;
    private void MyCode() { GetValue(dpBlah); }
}

DataGrid_AutoGeneratingColumn(...) {
    var oldBinding = (e.Column as DataGridBoundColumn).Binding;
    e.Column = new CustomTemplate { Header = e.PropertyName };
    BindingOperations.SetBinding(e.Column, dpBlah, oldBinding);
}

everything seems to run, but when MyCode() runs, GetValue has nothing. 一切似乎都在运行,但是当MyCode()运行时,GetValue没有任何东西。

Is there something I'm missing? 有什么我想念的吗? Why can't I get the value from the binding? 为什么不能从绑定中获取值?

You can set your property to the path of the binding and then use this path when you create the visual elements in your CustomTemplate class: 您可以将属性设置为绑定的路径,然后在CustomTemplate类中创建可视元素时使用此路径:

var oldBinding = (e.Column as DataGridBoundColumn).Binding as Binding;
e.Column = new CustomTemplate { Header = e.PropertyName, dpblah = oldBinding?.Path?.Path; };

In CustomTemplate , you could then get the value of the property for a specific item using reflection, eg: 然后在CustomTemplate ,您可以使用反射来获取特定项目的属性值,例如:

protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
    string bindingPath = dpblah;
    object value = dataItem.GetType().GetProperty(bindingPath).GetValue(dataItem);
    ...
}

If dataItem is a DataRowView you don't have to use reflection: 如果dataItemDataRowView ,则不必使用反射:

DataRowView drv = dataItem as DataRowView;
if(drv != null)
{
    object value = drv[bindingPath];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM