从ContentPresenter的DataTemplate后面的代码中访问一个命名的TextBox [英] Access a named TextBox in the code behind from a ContentPresenter's DataTemplate
问题描述
我试图通过WPF页面后面的代码访问名为 TextBox
(textBoxAnswer)的内容。麻烦在于,因为它是 DataTemplate
的一部分,所以它不会作为类的私有成员自动生成,就像如果我不使用 ContentPresenter
+ DataTemplate
。 (我正在使用 DataTemplate
,因为我需要使用 DataTrigger
s,下面的示例中未包含)。
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 DataTrigger
s, not included in the example below).
我尝试调用 FindResource( textBoxAnswer)
和 FindName( textBoxAnswer)
,但都不返回任何内容。
I have tried calling FindResource("textBoxAnswer")
and FindName("textBoxAnswer")
, but neither return anything.
有什么建议吗?这是我的XAML的精简版本:
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>
推荐答案
给 ContentPresenter
命名(我假设它是 cpAnswer
),然后使用模板的 FindName
方法:
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;
这篇关于从ContentPresenter的DataTemplate后面的代码中访问一个命名的TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!