Finding a DataTemplate Element programatically in DataGrid

Aug 14, 2009 at 1: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:DataGridTextColumn Header="First Name" IsReadOnly="True" Binding="{Binding Path=FirstName}">
                <my:DataGridTemplateColumn Header="Car">
                            <TextBlock Name="test" Text="{Binding Path=Car}">
I want to find the TextBlock "test" programatically in the code behind. Any suggestions?
Aug 14, 2009 at 12:05 PM

First you need to get to the DataGridCell that you want.  The code for that can be found on this thread,  After you have the cell, then you can access the TextBlock through DataGridCell.Content.

Aug 14, 2009 at 3:50 PM
Edited Aug 14, 2009 at 4: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.

Aug 17, 2009 at 12: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.