[英]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.