我基本上是在制作聊天功能,XAML 代码段如下所示:
<StackLayout Grid.Row="1" Orientation="Horizontal" HeightRequest="50">
<Entry x:Name="ChatField" Text="{Binding CurrentMessageText}" Placeholder="{Binding MessageTextPlaceHolder}" HorizontalOptions="FillAndExpand"/>
<Button Text="send" BackgroundColor="Transparent" Command="{Binding SendMessageCommand}"/>
</StackLayout>
我有一个 Entry 控件和一个按钮控件,它们绑定(bind)到在聊天字段中发送文本的命令。
我想模仿聊天应用程序标准,其中按下发送按钮不会取消焦点或隐藏键盘。
不幸的是,现在当我按下发送按钮时 - 它会自动将键盘从输入单元格中移开。
我为防止这种情况所做的初始步骤是在我拥有的 ViewModel SendMessageCommand 上:
var chatEntry = CurrentPage.FindByName<Entry>("ChatField");
chatEntry.Focus();
但这会导致将所有 ListView 向上推的奇怪行为。
最佳答案
在 IOS 上使用自定义渲染器解决了这个问题:
public class ChatEntryViewRenderer : EntryRenderer
{
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.IsFocusedProperty.PropertyName)
{
if (Control != null)
{
var chatEntryView = this.Element as ChatEntryView;
Control.ShouldEndEditing = (UITextField textField) =>
{
return !chatEntryView.KeepOpen; // KeepOpen is a custom property I added and is set on my ViewModel if I want the Entry Keyboard to be kept open then I just set this to true.
};
}
}
base.OnElementPropertyChanged(sender, e);
}
}
它的作用是基本上使用控件的 ShouldEndEditing 事件,该事件在 EditText 失去焦点或键盘即将失去焦点时触发。
关于c# - 如何防止 Xamarin.Forms.Entry 键盘在按下按钮时失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40571826/