FindName does not work

1.8k Views Asked by At

My FindName does not work, the value is null.
And I can't call my x:Name="QuantiteTextBox" in my code-behind...
The name seems to not exist in this context..

XAML :

<GridViewColumn Width="Auto" Header="Nb">
     <GridViewColumn.CellTemplate>
          <DataTemplate>
               <TextBox x:Name="QuantiteTextBox" Text="{Binding Quantite, ElementName=EditTableUserControl}" HorizontalAlignment="Center" Margin="-10,0,0,0"/>
          </DataTemplate>
     </GridViewColumn.CellTemplate>
</GridViewColumn>

WPF :

var quantiteTextBox = (TextBox)FindName("QuantiteTextBox");

How can I resolve this problem please ? Thanks.

1

There are 1 best solutions below

0
On

FindName won't work because the TextBox is in a template. That <TextBox> declaration isn't actually creating a TextBox named "QuantiteTextBox." Instead, GridViewColumn uses that TextBox as a template to create more TextBoxes. Imagine if that GridViewColumn was in a GridView with 10 rows. You might get 10 TextBox instances, so there is no single TextBox with that name.

When you call FindName, it queries a certain scope. If the code you posted is right inside a WPF Window, then it will look for controls inside that window only. Since that TextBox isn't in the window, you won't find it.

At this point, I don't know if you meant to find one of the TextBoxes in the Window, or if you really want the one in the control template. Take a look at t

See Why doesnt Window.FindName() discover the x:Name of a button in a child UserControl? AKA how do NameScopes work? for a better explanation than I can give. In short: You probably want to do this another way.