Get the controls inside DataTemplate control

前端 未结 1 720
别那么骄傲
别那么骄傲 2021-01-22 03:23

I have the following XAML code that used on hub application for windows 8.1:


                

        
1条回答
  •  没有蜡笔的小新
    2021-01-22 04:12

    You should use a VisualTreeHelper method. This is just some code I am using. I think you can easily adjust it to your needs.

    First put the FindElementByName method somewhere into your code behind file:

    public T FindElementByName(DependencyObject element, string sChildName) where T : FrameworkElement
        {
            T childElement = null;
            var nChildCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < nChildCount; i++)
            {
                FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
    
                if (child == null)
                    continue;
    
                if (child is T && child.Name.Equals(sChildName))
                {
                    childElement = (T)child;
                    break;
                }
    
                childElement = FindElementByName(child, sChildName);
    
                if (childElement != null)
                    break;
            }
            return childElement;
        }
    

    Now you can start using the method. Add an event handler to your MapLayer or to your Map like this:

    
    

    Inside your handler you can now access the element with code like this (you might have to adjust this as I am not too familiar with the Hubsection control):

    this.UpdateLayout();
    // Give your hub a name using x:Name=
    var item = [..] // Retrieve your hubsection here!
    var container = this.MyHubSection.ContainerFromItem(item);
    // NPE safety, deny first
    if (container == null)
        return;
    var datalayer = FindElementByName(container, "DataLayer");
    // And again deny if we got null
    if (datalayer == null)
        return;
    /*
      Start doing your stuff here.
    */
    

    0 讨论(0)
提交回复
热议问题