Access a named TextBox in the code behind from a ContentPresenter's DataTemplate
Asked Answered
I

1

1

I am trying to get access to a named TextBox (textBoxAnswer) in the code behind of my WPF Page. The trouble is, because it is part of a DataTemplate, it is not auto-generated as a private member of the class, like it would be if I wasn't using the ContentPresenter + DataTemplate. (I am using the DataTemplate because I need to use DataTriggers, not included in the example below).

I have tried calling FindResource("textBoxAnswer") and FindName("textBoxAnswer"), but neither 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>

Irrawaddy answered 12/9, 2009 at 18:20 Comment(0)
J
2

Give a name to the ContentPresenter (I will assume it is cpAnswer), and access the textbox with the FindName method of the template :

TextBox textBoxAnswer = cpAnswer.ContentTemplate.FindName("textBoxAnswer", cpAnswer) 
as TextBox;
Jacaranda answered 12/9, 2009 at 18:24 Comment(1)
brilliant, thanks! I have accepted the answer, but you had a small mistake which I have fixed - should be .ContentTemplate, not .DataTemplate. Also, should not be called in the constructor, but only after the page has loaded.Irrawaddy

© 2022 - 2024 — McMap. All rights reserved.