我正在尝试访问WPF页面后面代码中的命名 TextBox (textBoxAnswer)。麻烦的是,因为它是 DataTemplate 的一部分,它不是作为类的私有成员自动生成的,就像我没有使用 ContentPresenter + DataTemplate 。 (我正在使用 DataTemplate ,因为我需要使用 DataTrigger ,而不包含在下面的示例中。)

我尝试过调用 FindResource(" textBoxAnswer") FindName(" textBoxAnswer"),但都没有返回任何内容。

有什么建议吗?这是我的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 方法访问文本框:

TextBox textBoxAnswer = cpAnswer.ContentTemplate.FindName("textBoxAnswer", cpAnswer) 
as TextBox;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top