How to access xaml Control inside DataTemplate inside FlipView

别来无恙 提交于 2019-11-30 16:27:55
sankar

I have tried and I am able to access the control inside of FlipView DataTemplate as you described. Try to below approach and let me know if this helps.

public static IEnumerable<T> RecurseChildren<T>(DependencyObject root) where T : UIElement
{
    if (root is T)
    {
        yield return root as T;
    }

    if (root != null)
    {
        var count = VisualTreeHelper.GetChildrenCount(root);


        for (var idx = 0; idx < count; idx++)
        {
            foreach (var child in RecurseChildren<T>(VisualTreeHelper.GetChild(root, idx)))
            {
                yield return child;
            }
        }
    }
}

Accessing Image control:

var imageControl = RecurseChildren<Image>(rootVisual).FirstOrDefault();

here rootVisual is the Grid instance in my page.

Jerry Nixon

Answered here https://stackoverflow.com/a/16446670/265706

The short answer is: The problem you are experiencing is that the DataTemplate is repeating and the content is being generated by he FlipView. The Name is not exposed because it would conflict with the previous sibling that was generated (or the next one that will be).

So, to get a named element in the DataTemplate you have to first get the generated item, and then search inside that generated item for the element you want. Remember, the Logical Tree in XAML is how you access things by name. Generated items are not in the Logical Tree. Instead, they are in the Visual Tree (all controls are in the Visual Tree). That means it is in the Visual Tree you must search for the control you want to reference. The VisualTreeHelper lets you do this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!