将 ViewCell Entry 焦点放在 ListView 项目选择上

Edw*_*rey 5 listview xamarin.forms

我有一个带有自定义 ViewCell 的 Xamarin.Forms ListView,其中包含带有条目和标签的 StackLayout。我希望每次选择 ViewCell 时 Entry 都能获得焦点。

ItemSelected提供选定的项目,但不提供 ViewCell。我可以为 ViewCell 创建一个自定义类,但我不知道它如何知道何时选择它。

如何将 Entry 焦点集中在 ListView 项目选择上?

Edw*_*rey 4

将 Entry 移动到视图模型中,并将 Entry 绑定到ContentViewViewCell 中的 a。在ListView.ItemSelected事件处理程序中,SelectedItem现在包含 Entry,您可以在其上调用Focus.

XAML 如下所示:(在此示例中,Entry 保存一个数量。)

<ViewCell>
    <StackLayout Orientation="Horizontal">
        <ContentView Content="{Binding QuantityView}" />
        <Label ... />
    </StackLayout>
</ViewCell>
Run Code Online (Sandbox Code Playgroud)

视图模型如下所示:

public class MyViewModel {
    public string Quantity {get; set;}
    public Entry QuantityView { get; } = new Entry {...};

    public MyViewModel() {
        QuantityView.SetBinding(Entry.TextProperty, nameof(Quantity));
    }
}
Run Code Online (Sandbox Code Playgroud)

事件ItemSelected处理程序如下所示:

void FocusQuantity(object sender, SelectedItemChangedEventArgs e) {
    if (e.SelectedItem == null) return;
    ((MyViewModel)e.SelectedItem).QuantityView.Focus();
}
Run Code Online (Sandbox Code Playgroud)