问题
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