问题描述
我有一个列表框,其中包含由单个文本框表示的项目.
I have a list box that contains items that are represented by a single textbox.
当用户单击按钮时,我要遍历所有这些文本框,并检查它们的绑定表达式中是否包含错误;应该是这样的:
When the user clicks a button, I want to iterate thru all these text boxes and check if their binding expressions are clean of errors;Should be something like:
Dim errCount = 0
For Each item In MyListBox.ListBoxItems 'There is no such thing ListBoxItems which is actually what I am looking for.
Dim tb As TextBox = item '.........Dig in item to extract the textbox from the visual tree.
errCount += tb.GetBindingExpression(TextBox.TextProperty).HasError
Next
If errCount Then
'Errors found!
End If
任何讨论将不胜感激.谢谢.
Any discussion would be really appreciated.Thanks.
推荐答案
可能有更简单的方法,但这是一个可行的选择:
There may be an easier way to do this, but here is one option that will work:
1)遍历项目列表.
因为您正在使用项目源,所以ListBox.Items
将引用ItemsSource中的数据项目.
Because you are using items source, ListBox.Items
will refer to the data items in the ItemsSource.
for (int i = 0; i < ListBox.Items.Count; i++)
{
// do work as follows below...
}
2)获取这些物品的容器.
2) Get the containers for these items.
DependencyObject obj = ListBox.ItemContainerGenerator.ContainerFromIndex(i);
3)使用VisualTreeHelper搜索容器视觉的TextBox子级.
3) Use VisualTreeHelper to search for a TextBox child of the container visual.
TextBox box = FindVisualChild<TextBox>(obj);
使用此功能搜索正确类型的可视孩子:
Use this function to search for a visual child of the correct type:
public static childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
// Search immediate children
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
4)最后,检查TextBox上的绑定.
4) Finally, examine the binding on the TextBox.
全部放在一起,像这样:
All put together, something like this:
private bool ValidateList(ListBox lb)
{
for (int i = 0; i < lb.Items.Count; i++)
{
DependencyObject obj = lb.ItemContainerGenerator.ContainerFromIndex(i);
TextBox box = FindVisualChild<TextBox>(obj);
if (!TestBinding(box))
return false;
}
return true;
}
这篇关于有没有办法在ListBox Items模板中进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!