tags:

views:

393

answers:

1

I am trying to get access to a 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"&gt;
<ContentPresenter Content="{Binding}">
    <ContentPresenter.ContentTemplate>
        <DataTemplate>
            <Grid>
                <TextBox Margin="5" x:Name="textBoxAnswer"
                Text="{Binding Answer}" />
            </Grid>
        </DataTemplate>
    </ContentPresenter.ContentTemplate>
</ContentPresenter>

+1  A: 

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;
Thomas Levesque
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.
Mark Heath