Finding a DataTemplate Element programatically in DataGrid

Aug 14, 2009 at 2:01 AM
<my:DataGrid AutoGenerateColumns="False" Margin="12,24,0,132" Name="dataGrid1" HorizontalAlignment="Left" Width="260"
                     ItemsSource="{Binding Source={StaticResource PersonList}}" MouseRightButtonUp="dataGrid1_MouseRightButtonUp">
            <my:DataGrid.Columns>
                <my:DataGridTextColumn Header="First Name" IsReadOnly="True" Binding="{Binding Path=FirstName}">
                </my:DataGridTextColumn>
                <my:DataGridTemplateColumn Header="Car">
                    <my:DataGridTemplateColumn.CellTemplate> 
                        <DataTemplate>
                            <TextBlock Name="test" Text="{Binding Path=Car}">
                            </TextBlock>
                        </DataTemplate>
                    </my:DataGridTemplateColumn.CellTemplate>
           </my:DataGrid.Columns>
        </my:DataGrid>
I want to find the TextBlock "test" programatically in the code behind. Any suggestions?
Coordinator
Aug 14, 2009 at 1:05 PM

First you need to get to the DataGridCell that you want.  The code for that can be found on this thread, http://wpf.codeplex.com/Thread/View.aspx?ThreadId=34065.  After you have the cell, then you can access the TextBlock through DataGridCell.Content.

Aug 14, 2009 at 4:50 PM
Edited Aug 14, 2009 at 5:36 PM

Can you, please, give me more details? I have put the debugger on the DataGridCell.Content and I did not see any properties to access the textblock in code.

And I would like to clarify something so that your answer can be more complete. The reason I want to get to the TextBlock is so that I can set it to "readonly". However I have tried doing that on the "First Name" and the "IsReadOnly" property is "readonly" (I know; the irony...). Thus my question is: how do I get to an element (please give me a little bit more detail after the cell.content) and once I am there how do I set the property programatically?

thank you.

Coordinator
Aug 17, 2009 at 1:43 PM

The cell's Content in this case will be a ContentPresenter which will be the parent of TextBlock.  You can gain access to the TextBlock through the standard GetVisualChild pattern which is also on the thread I reference above.