This is a migrated thread and some comments may be shown as answers.

How to provide DataContext to Cells of autogenerated columns (FrameworkElement)?

1 Answer 148 Views
DataGrid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Mikhail
Top achievements
Rank 1
Mikhail asked on 25 Sep 2018, 05:04 PM

Good day. 

I use column auto-generation on the dynamic collection as a source.  Previous post link

But DataContext for generated Cell(FrameworkElement) is entire RowItem (System.Dynamic.ExpandoObject).

Thus, the problem is that the template does not know the names of the properties.

Therefore, I need to pass only one property to the datacontext of the cell and not the entire RowItem.

Maybe there is a way to somehow pass the binding on the current property for the entire column?

Or somehow in the code at generation of a cell to transfer to it the necessary datacotext property?

{
    public ObservableCollection<System.Dynamic.ExpandoObject> Items { get; set; }
}
 
<controls:RadDataGrid x:Name="TableViewRelatedObjects"
                    HorizontalAlignment="Stretch"
                    DataContext="{x:Bind ViewModel}"
                    ItemsSource="{x:Bind ViewModel.Items, Mode=OneWay}"
                    AutoGenerateColumns="True"
                    UserGroupMode="Disabled">
</controls:RadDataGrid>

 

private DataTemplateSelector _fieldTemplateSelector;
 
public CustomGenerateColumnCommand(DataTemplateSelector fieldTemplateSelector)
{
    this.Id = Telerik.UI.Xaml.Controls.Grid.Commands.CommandId.GenerateColumn;
 
    _fieldTemplateSelector = fieldTemplateSelector;
}
 
public override bool CanExecute(object parameter)
{
    var context = parameter as GenerateColumnContext;
    // put your custom logic here
    return true;
}
 
public override void Execute(object parameter)
{
    var context = parameter as GenerateColumnContext;
    var template = _fieldTemplateSelector.SelectTemplate(context.PropertyName);
 
    var column = new DataGridTemplateColumn()
        {
            CellContentTemplate = template
        };
 
    context.Result = column;
    return;
    };
}

 

1 Answer, 1 is accepted

Sort by
0
Didi
Telerik team
answered on 26 Sep 2018, 03:14 PM
Hi Mikhail,

I have created a sample example how to create a DataGridTemplateColumn and how to set the DataTemplateSelector to this column. Please take a look at the attached project inside this files: CustomDataTemplateSelector.cs, CustomGenerateColumnCommand.cs and MainPage.xaml.

I hope this could help.

Regards,
Didi
Progress Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
DataGrid
Asked by
Mikhail
Top achievements
Rank 1
Answers by
Didi
Telerik team
Share this question
or