0

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.

C0ZEN
  • 894
  • 11
  • 41
  • 1
    You sure you are using FindName on the right window? – AgentFire Feb 04 '15 at 21:11
  • Solution : http://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type/1759923#1759923 An alternative to the FindName. – C0ZEN Feb 04 '15 at 21:15

1 Answers1

1

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.

Community
  • 1
  • 1
Moby Disk
  • 3,761
  • 1
  • 19
  • 38