简体   繁体   中英

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>
                <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 . this button has a click event whose definition is present in the code behind cs file .

Problem : i want to access the textbox within the event handler of this button . How do i do it ?

You could use the 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?

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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