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

余生长醉 提交于 2019-12-11 17:41:53

问题


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>


回答1:


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;


来源:https://stackoverflow.com/questions/1415771/access-a-named-textbox-in-the-code-behind-from-a-contentpresenters-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!