【问题标题】:Access a named TextBox in the code behind from a ContentPresenter's DataTemplate从 ContentPresenter 的 DataTemplate 访问代码中的命名文本框
【发布时间】:2009-09-12 18:20:35
【问题描述】:

我试图在我的 WPF 页面后面的代码中访问名为 TextBox (textBoxAnswer)。问题是,因为它是DataTemplate 的一部分,所以它不会作为类的私有成员自动生成,就像我不使用ContentPresenter + DataTemplate 时一样。 (我使用DataTemplate是因为我需要使用DataTriggers,下面的例子中没有包含)。

我曾尝试调用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>

【问题讨论】:

    标签: wpf xaml textbox datatemplate


    【解决方案1】:

    ContentPresenter命名(我假设它是cpAnswer),并使用模板的FindName方法访问文本框:

    TextBox textBoxAnswer = cpAnswer.ContentTemplate.FindName("textBoxAnswer", cpAnswer) 
    as TextBox;
    

    【讨论】:

    • 太棒了,谢谢!我已经接受了答案,但你有一个我已经修复的小错误 - 应该是 .ContentTemplate,而不是 .DataTemplate。此外,不应在构造函数中调用,而只能在页面加载后调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2017-11-07
    • 2012-04-10
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多