原文:
WPF 获取 ListView DataTemplate 中控件值
版权声明:本文为博主原创文章,未经博主允许可以随意转载 https://blog.csdn.net/songqingwei1988/article/details/50475191
RT
虽然DataTemplate 是用来绑定的,一般用ONE TWOWAY 来绑定传递或获取数据.
但是今天这个需求真是没办法,在绑定的模板内添加了一个非绑定的数据,需要手动取值.
解决方案原理:
https://msdn.microsoft.com/zh-cn/library/bb613579.aspx
foreach (var item in FListView.Items)
{
var myListBoxItem = (ListViewItem)FListView.ItemContainerGenerator.ContainerFromItem(item);
// Getting the ContentPresenter of myListBoxItem
var myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
var obj = myDataTemplate.FindName("CheckNum", myContentPresenter);//CheckNum 是在模板内定义的 x:Name
var checkNum = obj as NumericControl;//自定义控件
if (checkNum != null)
{//...do something
}
}
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}