问题描述
我有一个C#应用商店应用程序,并使用DataTemplate选择器来确定要在绑定到数组的ListView控件中使用的模板类型。因为它是模板化的,所以我无法为每个ListView行分配一个动态的x:Name。
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.
我需要能够按索引访问listview行并设置将它们设置为打开或关闭。我已经尝试过类似的事情,但是 .ItemContainerGenerator
返回
.ContainerFromItem(item); null
并我每次都会收到Nullable异常:
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:
做完一些研究后,看来上述解决方案仅在我触摸或设置了SelectedItem时才有效。请参阅此处
After doing some research, it appears that the above solution only works if I touch or have SelectedItem set. See here
我需要能够在页面加载(初始设置)和按钮单击时调用方法,并修改某些行的可见性。 / p>
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.
推荐答案
这应该做您想要的事情:
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;
}
使用此功能:
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;
}
祝你好运!
这篇关于如何在不与其交互的情况下访问XAML DataTemplate Listview中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!