在我的代码中,
protected override void OnNavigatedTo(NavigationEventArgs e)
{
using (bus_noContext ctx = new bus_noContext(bus_noContext.ConnectionString))
{
ctx.CreateIfNotExists();
ctx.LogDebug = true;
var buses = from c in ctx.Bus_routes
select new bus_list{ BUS_NO = c.BUS_NO, SOURCE = c.SOURCE, DESTINATION = c.DESTINATION};
busno_list.ItemsSource = buses.ToList();
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string temp;
TextBlock nameBox;
ListBoxItem currentSelectedListBoxItem;
for(int i=0;i<busno_list.Items.Count;i++)
{
currentSelectedListBoxItem = this.busno_list.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
nameBox = FindDescendant<TextBlock>(currentSelectedListBoxItem);
temp = nameBox.Text;
if (temp.Contains(searchbox.Text))
{
busno_list.SelectedIndex = i;
busno_list.ScrollIntoView(busno_list.SelectedItem);
return;
}
}
}
在 FindDescendant 函数中,
private T FindDescendant<T>(DependencyObject obj) where T : DependencyObject
{
// Check if this object is the specified type
if (obj is T)
return obj as T;
// Check for children
int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
if (childrenCount < 1)
return null;
// First check all the children
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is T)
return child as T;
}
// Then check the childrens children
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = FindDescendant<T>(VisualTreeHelper.GetChild(obj, i));
if (child != null && child is T)
return child as T;
}
return null;
}
但是在
int childrenCount = VisualTreeHelper.GetChildrenCount(obj);
调试器总是抛出 InvalidOperationException(引用不是有效的可视 DependencyObject),并且在 Autos 监视工具中,obj 显示空值,即使列表框中已经有 557 行。
所以我无法纠正这个异常。
我发现这种方法最适合搜索具有数据模板的列表框,如如何使用 DataTemplate 访问列表框中的特定项目?. 请建议我哪里出错了,或者是否有更好的选择。