5

How to access control in DataGridTemplateColumn to get value ?

I'm using this code :

  <DataGrid HeadersVisibility="None"  Name="dgUser" Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" ItemsSource="{Binding}"
 CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False">
                                <DataGrid.Columns>
                                    <DataGridTemplateColumn Width="*" Header="" IsReadOnly="True">
                                        <DataGridTemplateColumn.CellTemplate>
                                            <DataTemplate>
                                                <StackPanel Orientation="Horizontal"  Margin="10,0,0,0" Grid.Column="0"  Name="partcount">
                                                    <TextBlock Margin="0,0,5,0" Text="Count"/>
                                                    <TextBox Margin="0,0,5,0" MinWidth="50" Width="Auto" Name="txtcount" Text="{Binding Count}"/>
                                                </StackPanel>
                                            </DataTemplate>
                                        </DataGridTemplateColumn.CellTemplate>
                                    </DataGridTemplateColumn>
       </DataGrid.Columns>
                            </DataGrid>

how to access txtcount ?

Vishal Pawar
  • 4,324
  • 4
  • 28
  • 54
user1799345
  • 99
  • 2
  • 7

1 Answers1

3

You will have to navigate the visual tree to find this element. I wrote a utility class a while back that makes this a little easier, using Linq-to-VisualTree you can find it as follows:

TextBox tb = dgUser.Descendants<TextBox>()
                   .OfType<TextBox>()
                   .Where(t => t.Name == "txtcount")
                   .Single();
ColinE
  • 68,894
  • 15
  • 164
  • 232
  • What cell would the TextBox show as result, the one on the first row right ? – HichemSeeSharp Nov 05 '12 at 06:37
  • error : Error 1 'System.Windows.Controls.DataGrid' does not contain a definition for 'Descendants' and no extension method 'Descendants' accepting a first argument of type 'System.Windows.Controls.DataGrid' could be found (are you missing a using directive or an assembly reference?) – user1799345 Nov 05 '12 at 06:38
  • 1
    @user1799345 Descendants() is an extension method that he wrote. follow the link that he provided. – Vale Nov 05 '12 at 07:10
  • @ColinE Do you have a new version for `.NET Core`? In `WPF Core`, I'm getting the following error with the exact same DataGrid the `OP` has above: `System.InvalidOperationException HResult=0x80131509 Message=Sequence contains no elements Source=System.Linq` – nam Aug 26 '20 at 22:54