Seaky Lone
Seaky Lone

Reputation: 1031

UWP VisualTreeHelper Wrong Parameter Reference

I want to modify the content in a TabItem of a TabView. And that TabItem uses DataTemplate.

When I am trying to access the children of that item like the following:

        var container = tabview.ContainerFromIndex(tabview.SelectedIndex);
        int count = VisualTreeHelper.GetChildrenCount(container);

I got the ArgumentException: Wrong Parameter Reference on the second line. How should I use VisualTreeHelper to modify it?

Upvotes: 0

Views: 212

Answers (1)

Thansy
Thansy

Reputation: 74

Here is a easy method:

public static T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
{
    DependencyObject child = null;
    T grandChild = null;

    for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
    {
        child = VisualTreeHelper.GetChild(obj, i);

        if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
        {
            return (T)child;
        }
        else
        {
            grandChild = GetChildObject<T>(child, name);
        }
        if (grandChild != null)
        {
            return grandChild;
        }
    }
    return null;
}

From your description, you can already get the container of the target element. Let's assume that the element you need is named TargetEle and the type is TextBlock. You can write it like this:

var target = GetChildObject<TextBlock>(container,"TargetEle");

Update

I tested your code and found that you didn't capture the events loaded by the page.

In fact, the SelectionChanged event is fired when the TabView is just created, but the visual tree is not loaded yet, and you can't get the content from it through the code. You can create an IsLoaded property in the page, set it to True when Page Loaded, and determine this property in the SelectionChanged time.

Only when it is True, proceed to the next step.

Upvotes: 2

Related Questions