简体   繁体   English

如何从位于DataTemplate标记外部的控件访问位于DataTemplate中的控件

[英]how to access control located in DataTemplate from a control located outside DataTemplate tag

Situation : i have a textbox control located within DataTemplate of <phone:Panorama.TitleTemplate> tags 情况 :我在<phone:Panorama.TitleTemplate>标签的DataTemplate中有一个文本框控件

<phone:Panorama.TitleTemplate>
            <DataTemplate>
                <TextBlock Text="select your problem"  Margin="7,40,0,0" 
                           FontSize="60" Foreground="{StaticResource PhoneForegroundBrush}"/>
            </DataTemplate>
</phone:Panorama.TitleTemplate>

now i have another button located outside of DataTemplate tag and within LayoutRoot Grid tag . 现在我有另一个按钮位于DataTemplate标签外部和LayoutRoot Grid标签内部。 this button has a click event whose definition is present in the code behind cs file . 此按钮有一个click事件,其定义在cs文件后面的代码中提供。

Problem : i want to access the textbox within the event handler of this button . 问题:我想访问此按钮的事件处理程序中的文本框。 How do i do it ? 我该怎么做 ?

You could use the VisualTreeHelper . 您可以使用VisualTreeHelper

Try this snippet which is for a listbox, you could modify it: 试试这个用于列表框的代码段,您可以对其进行修改:

public string option_selected = "";
public int check_count = 0;


public void SearchElement(DependencyObject targeted_control)
{
    var count = VisualTreeHelper.GetChildrenCount(targeted_control);   // targeted_control is the listbox
    if (count > 0)
    {
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targeted_control, i);
            if (child is TextBlock) // specific/child control 
            {
                TextBlock targeted_element = (TextBlock)child;
                if (targeted_element.IsChecked == true)
                {
                    if (targeted_element.Tag!= null)
                    {

                        option_selected = targeted_element.Tag.ToString();
                    }
                                            return;
                }
            }
            else
            {
                SearchElement(child);
            }
        }
    }
    else
    {
        return;
    }
}

This would be a great sample you could go through How to access a specific item in a Listbox with DataTemplate? 这将是一个很好的示例,您可以通过如何使用DataTemplate访问列表框中的特定项目?

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM