How to accessing Elements in XAML DataTemplate Listview without interacting with it

南楼画角 提交于 2019-12-01 10:29:46

问题


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!



来源:https://stackoverflow.com/questions/23645331/how-to-accessing-elements-in-xaml-datatemplate-listview-without-interacting-with

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