[英]Get Back List Item Control From Item Template WPF
I bind my list View with user controls as below, 我将列表视图与用户控件绑定如下,
<ListView Grid.Row="2" Name="lvItems">
<ListView.ItemTemplate>
<DataTemplate>
<my1:ucItem Name="li"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
That user control has local storage value that user will input at run time. 该用户控件具有用户将在运行时输入的本地存储值。 I don't want two way binding because, at run time that user control add another value other than user control is showing. 我不想双向绑定,因为在运行时,该用户控件会添加除用户控件之外的其他值。 I set up some get method to get back value stored in user control. 我设置了一些get方法来获取存储在用户控件中的值。 How can I get back that user control, lvItems.Items is just return Object List I bind to it, not my User Control. 我如何找回该用户控件lvItems.Items只是返回绑定到它的对象列表,而不是我的用户控件。 Is there a way to get back that generated User Control List. 有没有办法找回生成的用户控制列表。
for example, i want to read back ListView Items like that, 例如,我想像这样读回ListView项目,
foreach(UserControl uc in lvItems.Items){//Do Something}
@Amit is right in the comments, you should really use MVVM and a data binding approach. @Amit在注释中正确,您应该真正使用MVVM和数据绑定方法。 That said, if you are determined to do it the other way, this extension method should help: 就是说,如果您确定要采用其他方式,则此扩展方法应该会有所帮助:
public static class ItemsControlExtensions
{
public static IEnumerable<TElement> GetElementsOfType<TElement>(
this ItemsControl itemsControl, string named)
where TElement : FrameworkElement
{
ItemContainerGenerator generator = itemsControl.ItemContainerGenerator;
return
from object item in itemsControl.Items
let container = generator.ContainerFromItem(item)
let element = GetDescendantByName(container as FrameworkElement, named)
where element != null
select (TElement) element;
}
static FrameworkElement GetDescendantByName(FrameworkElement element,
string elementName)
{
if (element == null)
{
return null;
}
if (element.Name == elementName)
{
return element;
}
element.ApplyTemplate();
FrameworkElement match = null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
match = GetDescendantByName(child, elementName);
if (match != null)
{
break;
}
}
return match;
}
}
Usage would be like this: 用法如下:
foreach (UserControl uc in lvItems.GetElementsOfType<UserControl>(named: "li"))
{
// do something with 'uc'
}
The GetDescendantByName
method is based on one by Dr WPF from this blog post: ItemsControl: 'G' is for Generator . GetDescendantByName
方法基于WPF博士从此博客文章中获得的方法: ItemsControl:'G'用于Generator 。 In fact, that whole series of blog posts about how the ItemsControl
works is well worth a read: Dr WPF: ItemsControl: A to Z . 实际上,关于ItemsControl
如何工作的整个博客文章系列非常值得一读: WPF博士:ItemsControl:从A到Z。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.