Pergunta

Dentro de um evento, eu gostaria de colocar o foco em uma caixa de texto específico dentro modelo do ListViewItem. Os olhares XAML como este:

<ListView x:Name="myList" ItemsSource="{Binding SomeList}">
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <!-- Focus this! -->
                        <TextBox x:Name="myBox"/>

Eu tentei o seguinte no código por trás:

(myList.FindName("myBox") as TextBox).Focus();

mas eu parecem ter entendido mal os docs FindName(), porque ele retorna null.

Além disso, o ListView.Items não ajuda, porque isso (é claro) contém meus objetos de negócios consolidados e não ListViewItems.

Nem myList.ItemContainerGenerator.ContainerFromItem(item), que também retorna null.

Foi útil?

Solução

Para entender por que ContainerFromItem não funcionou para mim, aqui algum fundo. O manipulador de eventos onde eu precisava dessa funcionalidade esta aparência:

var item = new SomeListItem();
SomeList.Add(item);
ListViewItem = SomeList.ItemContainerGenerator.ContainerFromItem(item); // returns null

Depois do Add() o ItemContainerGenerator não cria imediatamente o recipiente, porque o evento CollectionChanged poderia ser tratada em um não-UI-thread. Em vez disso, inicia uma chamada assíncrona e aguarda o segmento interface do usuário para rechamada e executar a geração de controle ListViewItem real.

Para ser notificado quando isso acontece, o ItemContainerGenerator expõe um evento StatusChanged que é acionado depois que todos os recipientes são gerados.

Agora eu tenho que ouvir este evento e decidir se o controle atualmente querem é foco conjunto ou não.

Outras dicas

Como outros já mencionado, o MyBox TextBox não pode ser encontrada chamando FindName na ListView. No entanto, você pode obter o ListViewItem que está atualmente selecionado, e usar a classe VisualTreeHelper para obter o TextBox do ListViewItem. Para fazê-lo é algo como isto:

private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (myList.SelectedItem != null)
    {
        object o = myList.SelectedItem;
        ListViewItem lvi = (ListViewItem)myList.ItemContainerGenerator.ContainerFromItem(o);
        TextBox tb = FindByName("myBox", lvi) as TextBox;

        if (tb != null)
            tb.Dispatcher.BeginInvoke(new Func<bool>(tb.Focus));
    }
}

private FrameworkElement FindByName(string name, FrameworkElement root)
{
    Stack<FrameworkElement> tree = new Stack<FrameworkElement>();
    tree.Push(root);

    while (tree.Count > 0)
    {
        FrameworkElement current = tree.Pop();
        if (current.Name == name)
            return current;

        int count = VisualTreeHelper.GetChildrenCount(current);
        for (int i = 0; i < count; ++i)
        {
            DependencyObject child = VisualTreeHelper.GetChild(current, i);
            if (child is FrameworkElement)
                tree.Push((FrameworkElement)child);
        }
    }

    return null;
}

notei que o título da pergunta não se refere diretamente ao conteúdo da questão, e nem a resposta resposta aceitou. Eu tenho sido capaz de "acesso as ListViewItems de um WPF ListView" usando este:

public static IEnumerable<ListViewItem> GetListViewItemsFromList(ListView lv)
{
    return FindChildrenOfType<ListViewItem>(lv);
}

public static IEnumerable<T> FindChildrenOfType<T>(this DependencyObject ob)
    where T : class
{
    foreach (var child in GetChildren(ob))
    {
        T castedChild = child as T;
        if (castedChild != null)
        {
            yield return castedChild;
        }
        else
        {
            foreach (var internalChild in FindChildrenOfType<T>(child))
            {
                yield return internalChild;
            }
        }
    }
}

public static IEnumerable<DependencyObject> GetChildren(this DependencyObject ob)
{
    int childCount = VisualTreeHelper.GetChildrenCount(ob);

    for (int i = 0; i < childCount; i++)
    {
        yield return VisualTreeHelper.GetChild(ob, i);
    }
}

Eu não tenho certeza de como agitado a recursão fica, mas pareceu funcionar bem no meu caso. E não, eu não usei yield return num contexto recursiva antes.

Você pode atravessar a ViewTree para encontrar o item ' ListViewItem ' conjunto de registos que corresponde à célula desencadeada a partir de teste de ocorrência.

Da mesma forma, é possível obter os cabeçalhos das colunas da vista pai para comparar e combinar coluna da célula. Você pode querer vincular o nome da célula para o nome do cabeçalho de coluna como a chave para o seu comparador de delegado / filtro.

Por exemplo: HitResult está em TextBlock mostrado em verde. Você deseja obter o identificador para a ' ListViewItem .

enter descrição da imagem aqui

/// <summary>
///   ListView1_MouseMove
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListView1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) {
  if (ListView1.Items.Count <= 0)
    return;

  // Retrieve the coordinate of the mouse position.
  var pt = e.GetPosition((UIElement) sender);

  // Callback to return the result of the hit test.
  HitTestResultCallback myHitTestResult = result => {
    var obj = result.VisualHit;

    // Add additional DependancyObject types to ignore triggered by the cell's parent object container contexts here.
    //-----------
    if (obj is Border)
      return HitTestResultBehavior.Stop;
    //-----------

    var parent = VisualTreeHelper.GetParent(obj) as GridViewRowPresenter;
    if (parent == null)
      return HitTestResultBehavior.Stop;

    var headers = parent.Columns.ToDictionary(column => column.Header.ToString());

    // Traverse up the VisualTree and find the record set.
    DependencyObject d = parent;
    do {
      d = VisualTreeHelper.GetParent(d);
    } while (d != null && !(d is ListViewItem));

    // Reached the end of element set as root's scope.
    if (d == null)
      return HitTestResultBehavior.Stop;

    var item = d as ListViewItem;
    var index = ListView1.ItemContainerGenerator.IndexFromContainer(item);
    Debug.WriteLine(index);

    lblCursorPosition.Text = $"Over {item.Name} at ({index})";

    // Set the behavior to return visuals at all z-order levels.
    return HitTestResultBehavior.Continue;
  };

  // Set up a callback to receive the hit test result enumeration.
  VisualTreeHelper.HitTest((Visual)sender, null, myHitTestResult, new PointHitTestParameters(pt));
}

Nós usamos uma técnica similar com o novo datagrid do WPF:

Private Sub SelectAllText(ByVal cell As DataGridCell)
    If cell IsNot Nothing Then
        Dim txtBox As TextBox= GetVisualChild(Of TextBox)(cell)
        If txtBox IsNot Nothing Then
            txtBox.Focus()
            txtBox.SelectAll()
        End If
    End If
End Sub

Public Shared Function GetVisualChild(Of T As {Visual, New})(ByVal parent As Visual) As T
    Dim child As T = Nothing
    Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
    For i As Integer = 0 To numVisuals - 1
        Dim v As Visual = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)
        If v IsNot Nothing Then
            child = TryCast(v, T)
            If child Is Nothing Then
                child = GetVisualChild(Of T)(v)
            Else
                Exit For
            End If
        End If
    Next
    Return child
End Function

A técnica deve ser bastante aplicável para você, basta passar o seu listviewitem uma vez que é gerado.

Ou pode ser simplesmente feito por

private void yourtextboxinWPFGrid_LostFocus(object sender, RoutedEventArgs e)
    {
       //textbox can be catched like this. 
       var textBox = ((TextBox)sender);
       EmailValidation(textBox.Text);
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top