在 Windows Phone 7 中访问列表框中的项目
本文关键字:项目 列表 访问 Phone Windows | 更新日期: 2023-09-27 18:30:33
在我的代码中,
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;
}
}
}
而在查找后代函数中,
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(引用不是有效的可视依赖对象),并且在自动监视工具中,obj 显示空值,即使列表框中已经有 557 行。
所以我无法纠正这个异常。
我发现这种方法最适合搜索具有数据模板的列表框,如如何使用数据模板访问列表框中的特定项目?。请建议我哪里出错了,或者是否有更好的选择。
不确定为什么当你有源代码时,你试图通过查找生成的元素来做到这一点,即类似的东西:
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();
searchbox.Text = buses[20].SOURCE; // or whatever
}
}