Access the named TextBox in the code behind the DataTemplate ContentPresenter

I am trying to access a named TextBox (textBoxAnswer) in the code behind my WPF page. The problem is that it is part of the DataTemplate , it is not auto-generated as a private member of the class, as if I were not using ContentPresenter + DataTemplate . (I use a DataTemplate because I need to use a DataTrigger s, not included in the example below).

I tried calling FindResource("textBoxAnswer") and FindName("textBoxAnswer") , but did not return anything.

Any suggestions? Here is a stripped down version of my XAML:

 <Page x:Class="LearningGames.Numbers.NumbersPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ContentPresenter Content="{Binding}"> <ContentPresenter.ContentTemplate> <DataTemplate> <Grid> <TextBox Margin="5" x:Name="textBoxAnswer" Text="{Binding Answer}" /> </Grid> </DataTemplate> </ContentPresenter.ContentTemplate> </ContentPresenter> 

0
source share
1 answer

Give the name ContentPresenter (I assume it is cpAnswer ), and access the text field using the FindName method of the template:

 TextBox textBoxAnswer = cpAnswer.ContentTemplate.FindName("textBoxAnswer", cpAnswer) as TextBox; 
+1
source

Source: https://habr.com/ru/post/988991/


All Articles