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

DataContext in a DataGridTemplateColumn?

3 Answers 908 Views
Grid for XAML
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Shawn
Top achievements
Rank 1
Shawn asked on 25 Jun 2013, 06:10 AM
I am building a DataTemplate and I expected setting the DataContext inside the cell template would work, but it doesn't. This is what I am trying:

<DataTemplate>
  <StackPanel DataContext="{Binding Item}">
    <TextBlock Text="{Binding Name}" />
    <TextBlock Text="{Binding Price}" />
  </StackPanel>
</DataTemplate>

If I change it to this it works but for a complex piece of code that's a lot of children objects:

<DataTemplate>
  <StackPanel>
    <TextBlock Text="{Binding Item.Name}" />
    <TextBlock Text="{Binding Item.Price}" />
  </StackPanel>
</DataTemplate>

Shouldn't this work?

3 Answers, 1 is accepted

Sort by
0
Accepted
Ivaylo Gergov
Telerik team
answered on 25 Jun 2013, 08:31 AM
Hi Shawn,

Thank you for your question.

The UI Virtualization of RadDataGrid explicitly sets the DataContext of the root element in each cell to the ViewModel instance that represents the row. Therefore, <StackPanel DataContext="{Binding Item}"> will not work as the Binding will get overridden. If we only had the FrameworkElement.GetBindingExpression API we would have been more flexible here.

Anyways, to achieve the desired goal I suggest you add another object as a root element of the template. For example, this should work properly:
<DataTemplate>
    <Border>
       <StackPanel DataContext="{Binding Item}">
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Price}" />
       </StackPanel>
    </Border>
</DataTemplate>

I hope this is useful. Let me know should you have any other questions.


Regards,
Ivaylo Gergov
Telerik
Have a suggestion or face a problem - you can use the Ideas & Feedback portal to submit ideas, feedback and vote for them.
0
Shawn
Top achievements
Rank 1
answered on 25 Jun 2013, 08:36 AM
Great thanks!
0
majid malik
Top achievements
Rank 1
answered on 14 Jun 2019, 10:20 AM

Can anybody provide a sampe where a RadGridView has

1) A few templated columns

2) Each column has a copy of a celltemplate which is hosting a usercontrol

3) The usercontrol gets the column and row of the cell during grid binding operation and populates the cell with it own data.

4) then with the horizontal scrolling of the grid the data in the cells remains the same.

thankx in advance

Tags
Grid for XAML
Asked by
Shawn
Top achievements
Rank 1
Answers by
Ivaylo Gergov
Telerik team
Shawn
Top achievements
Rank 1
majid malik
Top achievements
Rank 1
Share this question
or