c# - 如何防止 Xamarin.Forms.Entry 键盘在按下按钮时失去焦点

标签 c# xaml xamarin xamarin.forms

我基本上是在制作聊天功能,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)到在聊天字段中发送文本的命令。

我想模仿聊天应用程序标准,其中按下发送按钮不会取消焦点或隐藏键盘。

enter image description here

不幸的是,现在当我按下发送按钮时 - 它会自动将键盘从输入单元格中移开。

我为防止这种情况所做的初始步骤是在我拥有的 ViewModel SendMessageCommand 上:

var chatEntry = CurrentPage.FindByName<Entry>("ChatField");
chatEntry.Focus();

但这会导致将所有 ListView 向上推的奇怪行为。

enter image description here

最佳答案

在 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/

相关文章:

c# - 使用 Infragistics UltraDateTimeEditor for WinForms 查看时间

silverlight - Silverlight 控件中的平铺图像

c# - 我应该如何使用 xamarin 表单在 android 上创建主要 Activity 以支持画中画模式?

ios - 将带有列表的 map 添加到移动应用程序的表单?

ios - Xamarin iOS - 我们如何以编程方式将辅助功能焦点设置为按钮

c# - 无法通过 .NET System.Xml.Xsl.XslCompiledTransform 将 XML 转换为 HTML

c# - 如何通过 System.Data.SQLite 检索 F# 查询表达式的 SQL 查询字符串?

.net - 我可以使用枚举作为 ConverterParameter 吗?

c# - 使用 x 和 y 坐标的二维单元格位置

c# - 在 WPF 表单上创建可变数量的文本框