.NET MAUI:使 Entry 像编辑器一样扩展到多行,但防止 Enter 上换行

问题描述 投票:0回答:1

在 .NET MAUI 应用程序中,我需要一个文本输入控件,该控件以单行输入开始,但当文本超出水平空间时自动扩展为多行。此外,此控件应防止用户使用“Enter”键手动输入新行。标准条目不会自动扩展,编辑器允许手动换行。因此,两者都不能完全满足要求。我想知道是否有现有的解决方法,或者我是否需要编写自定义处理程序。

最初使用 Entry 进行文本输入,预计它可以满足单行输入的需求,而不允许用户使用“Enter”键添加新行。为了适应用户输入冗长文本的情况,我希望条目自动扩展到下一行,类似于聊天应用程序的行为。我预计当文本输入到达可用行空间的末尾时,条目的高度会增加。

但是,当我尝试使用编辑器时,它不符合我的需求,因为它允许用户通过按“Enter”键手动创建新行。

editor maui multiline
1个回答
0
投票

在 .NET MAUI 应用程序中实现所需的功能,其中文本输入控件以单行输入开始,但当文本超出水平空间时自动扩展为多行,同时防止用户使用“Enter”手动输入新行“关键,您可能确实需要实施自定义解决方案。

一种方法是通过组合条目和编辑器的功能来创建自定义控件。您可以使用 Entry 控件来处理单行输入并根据内容动态调整其高度,然后在文本超出可用水平空间时切换到类似编辑器的控件。

using Microsoft.Maui.Controls;

命名空间您的命名空间 { 公共类 AutoExpandingTextInput :ContentView { 条目条目; 编辑编辑;

    public AutoExpandingTextInput()
    {
        InitializeControls();
        Content = entry;
    }

    void InitializeControls()
    {
        entry = new Entry
        {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.Start
        };

        editor = new Editor
        {
            HorizontalOptions = LayoutOptions.FillAndExpand,
            VerticalOptions = LayoutOptions.Start,
            IsVisible = false // Initially hide the Editor
        };

        entry.TextChanged += Entry_TextChanged;
        editor.TextChanged += Editor_TextChanged;
        editor.Completed += Editor_Completed;
    }

    void Entry_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Check if the width of the entry exceeds available space
        if (entry.Measure(double.PositiveInfinity, double.PositiveInfinity).Request.Width > entry.Width)
        {
            // Switch to Editor control
            entry.IsVisible = false;
            editor.Text = entry.Text;
            editor.IsVisible = true;
        }
    }

    void Editor_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Adjust height of the custom control based on Editor content
        // Add your logic to adjust height as needed
    }

    void Editor_Completed(object sender, EventArgs e)
    {
        // Handle completion action, if needed
    }
}

}

请注意,此示例提供了一个基本框架,您可能需要根据您的具体要求和 .NET MAUI 应用程序的布局进一步完善和自定义它。

© www.soinside.com 2019 - 2024. All rights reserved.