How to accessing Elements in XAML DataTemplate Lis

2020-03-30 07:39发布

问题:

I have a C# Store App and using DataTemplate Selectors to determine which type of Template to use in a ListView Control bound to an Array. Because it is templated, I cannot assign a dynamic x:Name to each ListView Row.

I need to be able to access the listview rows by Index and set the Visibility of them to On or Off. I have tried things like this, but the .ItemContainerGenerator .ContainerFromItem(item); return null and I get a Nullable exception every time:

How do I access a control inside a XAML DataTemplate?

After doing some research, it appears that the above solution only works if I touch or have SelectedItem set. See here

Why does ItemContainerGenerator return null?

I need to be able to Call a Method, both on Page load(initial setting) and also on button click and modify certain rows visibility.

回答1:

This should do what you want:

var items = grid.ItemsSource as IEnumerable<MyModel>;
foreach (var item in items)
{
    var container = grid.ContainerFromItem(item);
    var button = Children(container)
        .Where(x => x is Button)
        .Select(x => x as Button)
        .Where(x => x.Name.Equals("MyButton"))
        .FirstOrDefault();
    if (button == null)
        continue;
    if (item.ShouldBeVisible)
        button.Visibility = Visibility.Visible;
    else
        button.Visibility = Visibility.Collapsed;
}

Using this:

public List<Control> Children(DependencyObject parent)
{
    var list = new List<Control>();
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is Control)
            list.Add(child as Control);
        list.AddRange(Children(child));
    }
    return list;
}

Best of luck!