2010-05-07 3 views
0

사용자 지정 형식 VariableValueViewModel 개체의 컬렉션 (VariableValueCollection)이 ListView와 바인딩되어 있습니다. WPF 따르기 :동적으로 생성 된 TextBox 요소 검색 및 포커스

내 목표는 마지막 행에서 "Enter"키를 누를 때 새 행을 추가하고 새 행에 초점을 맞 춥니 다. 그렇게하기 위해, 나는 그 행이 마지막 행인지 확인하고 그 경우에 새로운 행을 추가한다.

private void tbValue_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == System.Windows.Input.Key.Enter) 
     { 

      DependencyObject obj = itemList.ContainerFromElement((sender as TextBox));     
      int index = itemList.ItemContainerGenerator.IndexFromContainer(obj); 
      if(index == (VariableValueCollection.Count - 1)) 
      { 
       // Create a VariableValueViewModel object and add to collection. In binding, that create a new list item with a new TextBox 
       ViewModel.AddNewRow(); 

       // How to set cursor and focus last row created? 
      } 

     } 
    } 

답변

0
나는 당신의 문제를 오해 할 수 있지만 이후로 당신이 VariableValueCollection에 ListView에 바인딩하는

, 변경 :하지만 새로운 텍스트 상자 ... keypressed를 방법 여기

을 집중하는 방법을 모른다 당신은 기본 컬렉션에 귀하의 ListView 반영됩니다.

당신은 그냥 할 수 귀하를 keyDown 이벤트 처리기에서 같이해야합니다 :

var newItem = new VariableValueViewModel(); 
VariableValueCollection.Add(newItem); 

itemList.SelectedItem = newItem; 

편집 :

아래의 방법은 당신이에서 자식 컨트롤을 찾을 수 있습니다 : 텍스트 상자를 집중하는 방법 시각적 트리 :

/// <summary> 
/// Finds the first child in the visual tree by type. 
/// </summary> 
public static T TryFindChild<T>(DependencyObject parent, Func<T, bool> predicate = null) where T : class { 
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { 
     var child = VisualTreeHelper.GetChild(parent, i); 
     if ((child is T) && (predicate!=null && predicate(child as T))) { 
      return (T)((object)child); 
     } else { 
      T result = TryFindChild<T>(child, predicate); 
      if (result != null) 
       return result; 
     } 
    } 
    return null; 
} 

지금 당신은 같은 것을 할 수 있습니다

itemList.ItemContainerGenerator.ContainerFromItem(newItem); 
TextBox textBox = TryFindChild<TextBox>(newItem) as TextBox; 
if (textBox != null) { 
    textBox.Focus(); 
} 
+0

사실, 내 컬렉션에 추가하는 모든 항목은 바인딩을 통해 ListBox에 새 TextBox를 만듭니다. 알려진 항목, 깜박이는 편집 커서를 관련 TextBox에 어떻게 넣을 수 있습니까? – user335444

+0

나는 이것을 할 수있는 방법으로 위의 나의 대답을 업데이트했다. –

관련 문제