Xamarin.Forms EntryCell SetFocus

时间:2014-11-27 16:16:39

标签: focus xamarin.forms

Xamarin.Forms

在TableView中设置焦点在EntryCell上

我如何......

EntryCell.Focus();

因为那不存在......我看过一篇关于可能正在做的帖子

EntryCell.Keyboard = null;

这是正确的,还是有更好的东西?

2 个答案:

答案 0 :(得分:2)

我发现的问题是,实际需要获得焦点的单元格中的基础字段在EntryCell类中不可用。我通过使用EntryCellRenderer自定义布局来实现此功能,以及依赖于子视图层次结构的特定顺序的脏黑客。此示例适用于iOS。您需要为需要支持的每个平台重做此项。

为EntryCell定义特定的子类

public class FocusableEntryCell: EntryCell
{
    public bool ShouldGetFocus = false;
    public FocusableEntryCell ()
    {
    }
}

创建渲染器并将其导出

[assembly: ExportRenderer (typeof (FocusableEntryCell), typeof (FocusableEntryCellRenderer))]

public class FocusableEntryCellRenderer: EntryCellRenderer
{
    public override UITableViewCell GetCell (Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var cell = base.GetCell (item, reusableCell, tv);
        var castCell = (FocusableEntryCell)item;
        // Bit of a hack below, but EntryCellRenderer.EntryCellTableViewCell is a private class so 
        // we can't access the TextField via a defined accessor - we have to know the subview hierarchy
        UITextField textField = (UITextField)cell.ContentView.Subviews [0];
        if (castCell.ShouldGetFocus) {
            textField.BecomeFirstResponder ();
        }
        return cell;
    }
}

创建单元格时,将焦点设置为您想要获得焦点的焦点

var cell = new FocusableEntryCell {
    Label = "My cell",
    ShouldGetFocus = true
};

答案 1 :(得分:0)

另一种方法是创建一个包含Label和类似条目的自定义ViewCell

public class MyCustomEntryCell : ViewCell
{
    public Label Label
    {
        get;
        set; 
    }

    public Entry Entry
    {
        get;
        set;
    }

    public MyCustomEntryCell
    {
         Label = new Label(); 
         Entry = new Entry(); 
         View = new StackLayout
         {
             Children =
             {
                 Label,
                 Entry  
             }
         }
    }

}`

然后调用MyCustomEntryCell.Entry.Focus()

而不是调用EntryCell.Focus()