[英]How to get User Control in listbox data template item
我试图在列表框中添加用户控件,但找不到正确的方法来获取它。
我在下面使用绑定列表框查找用户控件,但在10个项目中找不到3或4。
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = System.Windows.Media.VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = System.Windows.Media.VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
单击按钮的代码以查找用户控件。
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!downloadClicked)
{
downloadClicked = true;
SuraWithProgressBar prg = null;
ListBoxItem item = null;
for (int rowIndex = 0; rowIndex < lsbQuranData.Items.Count; rowIndex++)
{
item = this.lsbQuranData.ItemContainerGenerator.ContainerFromIndex(rowIndex) as ListBoxItem;
if (item != null)
{
prg = FindFirstElementInVisualTree<SuraWithProgressBar>(item);
if (prg != null)
{
//Do Somthing
prg.addButtonClickInterface(this);
}
}
}
}
else
MessageBox.Show("Please wait, downloading...");
}
正如我在10中提到的那样,它找不到3-4个项目。 我正在寻找在列表框内找到我的用户控件的正确方法。
谢谢!
经过很多头痛之后,我在以下两个链接中找到了解决方案:
WP7-VisualTreeHelper遍历所有ListBox项
http://msdn.microsoft.com/zh-CN/library/windows/apps/jj709920.aspx
将模板添加到列表框中,然后将SerializeStackPanel更改为StackPanel,即可解决问题。 请确保将其添加到ItemTemplate部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.