ListView - 将焦点设置在新行(UWP)中的控件上

时间:2016-10-14 15:41:40

标签: c# .net listview uwp

我有一个由ListView支持的ObservableCollection。用户可以添加一个新行,在代码中我向集合中添加一个新对象:array.Add(obj)

现在我要做的是将焦点放在新行中的TextBox上。问题是我相信我需要等到创建用户界面,而且我不知道有什么事情可以让我知道新行准备好了。

我已尝试在TextBox中获取新容器和对ListView_SelectionChanged的引用,但我在新行上获得了null返回值。

我已尝试使用ListViewItem.Loaded,但似乎没有为回收的行调用。

我也试过ListViewItem.GotFocus,但在代码中添加新行后没有调用。

如果我知道ListViewItem上的控件何时准备就绪,我就可以找到TextBox并设置其焦点。

也许我让它变得比它需要的更难,但我不确定如何继续。

1 个答案:

答案 0 :(得分:1)

我回答了自己的问题。以下是我提出的建议。

Xaml :(向Grid添加两个事件处理程序)

<DataTemplate x:Key="MyTemplate" x:DataType="model:Card">
    <Grid GotFocus="ListViewGrid_GotFocus" DataContextChanged="ListViewGrid_DataContextChanged">
        <StackPanel Orientation="Horizontal">
            <TextBox Name="Text1" Text="{x:Bind Text1}" />
        </StackPanel>
    </Grid>
</DataTemplate>

代码:

MyListView.Items.VectorChanged += ListViewItems_VectorChanged; // in constructor

private void AddRow_Click(object sender, RoutedEventArgs e) {

    card = ....
    _newRowCard = card;
    _array.Add(card);
}

private void ListViewItems_VectorChanged(IObservableVector<object> sender, IVectorChangedEventArgs @event) {

    // If new row added, at this point we can safely select and scroll to new item
    if (_newRowCard != null) {
        MyListView.SelectedIndex = MyListView.Items.Count - 1; // select row
        MyListView.ScrollIntoView(MyListView.Items[MyListView.Items.Count - 1]);   // scroll to bottom; this will make sure new row is visible and that DataContextChanged is called
    }
}

private void ListViewGrid_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) {

    // If new row added, at this point the UI is created and we can set focus to text box 
    if (_newRowCard != null) {
        Grid grid = (Grid)sender;
        Card card = (Card)grid.DataContext;  // might be null
        if (card == _newRowCard) {
            TextBox textBox = FindControl<TextBox>(grid, typeof(TextBox), "Text1");
            if (textBox != null) textBox.Focus(FocusState.Programmatic);
            _newRowCard = null;
        }
    }
}

private void ListViewGrid_GotFocus(object sender, RoutedEventArgs e) {
    // If user clicks on a control in the row, select entire row
    MyListView.SelectedItem = (sender as Grid).DataContext;
}

public static T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement {

    if (parent == null) return null;
    if (parent.GetType() == targetType && ((T)parent).Name == ControlName) return (T)parent;

    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < count; i++) {
        UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
        T result = FindControl<T>(child, targetType, ControlName);
        if (result != null) return result;
    }
    return null;
}