Pergunta

Eu tenho uma caixa de listagem que contém itens que são representados por uma única caixa de texto.

Quando o usuário clica em um botão, eu quero fazer uma iteração através de todas essas caixas de texto e verificar se suas expressões de ligação estão limpas de erros; Deve ser algo como:

    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

Qualquer discussão seria muito apreciada. Obrigado.

Foi útil?

Solução

Pode haver uma maneira mais fácil de fazer isso, mas aqui é uma opção que vai funcionar:

1) percorrer a lista de itens.

Como você está usando itens de origem, ListBox.Items vai referem-se aos itens de dados no ItemsSource.

for (int i = 0; i < ListBox.Items.Count; i++)
{
    // do work as follows below...
}

2) Obter os recipientes para esses itens.

DependencyObject obj = ListBox.ItemContainerGenerator.ContainerFromIndex(i);

3) Use VisualTreeHelper para procurar uma criança TextBox do recipiente visual.

TextBox box = FindVisualChild<TextBox>(obj);

Use esta função para procurar uma criança visual do tipo correto:

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) Por fim, examinar a ligação na caixa de texto.

Todos juntos, algo como isto:

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;
}

Outras dicas

Tradução de post anterior para VB:

1)

For i As Integer = 0 To ListBox.Items.Count - 1 
    ' do work as follows below... 
Next

2)

Dim obj As DependencyObject = ListBox.ItemContainerGenerator.ContainerFromIndex(i)

3)

Dim box As TextBox = FindVisualChild(Of TextBox)(obj)
'************************
Public Shared Function FindVisualChild(Of ChildItem As DependencyObject)(ByVal obj As DependencyObject) As ChildItem
    ' Search immediate children 
    For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
        Dim child As DependencyObject = VisualTreeHelper.GetChild(obj, i)
        If TypeOf child Is ChildItem Then
            Return child
        Else
            Dim childOfChild As ChildItem = FindVisualChild(Of ChildItem)(child)
            If childOfChild IsNot Nothing Then Return childOfChild
        End If
    Next
    Return Nothing
End Function

4)

Private Function ValidateList(ByVal lb As ListBox) As Boolean 
For i As Integer = 0 To lb.Items.Count - 1 
    Dim obj As DependencyObject = lb.ItemContainerGenerator.ContainerFromIndex(i) 
    Dim box As TextBox = FindVisualChild(Of TextBox)(obj) 
    If Not TestBinding(box) Then 
        Return False 
    End If 
Next 
Return True 

Função End

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top