简体   繁体   English

如何使用 XAML 和 C# 在 UWP 中设置文本框中的行数限制

[英]How can I set limit of Lines in TextBox in UWP using XAML and C#

I want to set the maximum number of lines in Textbox that has TextWrap enabled.我想设置启用 TextWrap 的文本框中的最大行数。 I tried multiple place for this answer but I failed.我为这个答案尝试了多个地方,但我失败了。 Please help me to find the answer.请帮我找到答案。

UPDATE: The current solutions suggest either counting the total number of characters or splitting the content by line breaks and counting the lines, but these solutions do not provide the expected result when text wrapping is enabled.更新:当前的解决方案建议计算字符总数或按换行符拆分内容并计算行数,但这些解决方案在启用文本换行时无法提供预期结果。

So basically you can count of the lines and do some limitations.所以基本上你可以计算行数并做一些限制。 To count the lines use this code:要计算行数,请使用以下代码:

    private void editBox_TextChanged(object sender, RoutedEventArgs e)
    {
        string _text;
        editBox.Document.GetText(TextGetOptions.None, out _text);

        int t = _text.Split('\n').Length;  
        if(t > 9)
        {
            Debug.WriteLine("Limit reached");
            //your code here
        }
    }

This is a basic code, but the principals are the same.这是一个基本的代码,但原理是一样的。 To limit the lines you can disable further insertion of new line char, or other limitations.要限制行,您可以禁用进一步插入新行字符或其他限制。

How can I set limit of Lines in TextBox in UWP using XAML and C#如何使用 XAML 和 C# 在 UWP 中设置文本框中的行数限制

There is no way to do this perfectly in UWP TextBox.在 UWP TextBox 中没有办法完美地做到这一点。 Different from the TextBox of WPF which has a TextBox.MaxLines Property , the TextBox class in UWP doesn't have such a built-in property.与 WPF 的 TextBox 具有TextBox.MaxLines 属性不同,UWP 中的 TextBox class 没有这样的内置属性。 Like what the @10 Devlops said, you need to do this on your own.就像@10 Devlops 所说的那样,您需要自己做这件事。

Besides the solution @10 develops provides, my suggestion is to use the TextBox.MaxLength Property which could limit the max length of the text in the TextBox.除了@10 开发提供的解决方案之外,我的建议是使用TextBox.MaxLength 属性,它可以限制 TextBox 中文本的最大长度。 You could combine this property with the solution @10 develops provides to get a new solution that depends on your own scenario.您可以将此属性与 @10 开发提供的解决方案结合使用,以获得取决于您自己的方案的新解决方案。

Text wrapping adds a new dimension to restricting the number of lines in a TextBox, to do so we need be aware that the number of lines can be affected by the resolution and zooming factor applied at the operating system level, but also many layout concepts utilised in UWP layout are generally relative or dynamic and affect the visual state is ways that are hard to keep consistent for all users.文本换行为限制 TextBox中的行数增加了一个新维度,为此我们需要注意行数可能会受到操作系统级别应用的分辨率和缩放因子的影响,而且还使用了许多布局概念在 UWP 布局通常是相对的或动态的,并影响视觉 state 是难以为所有用户保持一致的方式。

For instance, text that just fits on two lines in one user's runtime, might easily wrap into 3 lines for another user or when the width of the form is changed.例如,在一个用户的运行时中仅适合两行的文本可能很容易为另一个用户换成 3 行,或者当表单的宽度发生变化时。

Even after doing your best to limit a wrapped text box to a specific number of lines, we have to expect that over time, we will get it wrong, if the number of lines is important for layout reasons then you might consider trimming or truncating the text or even using RichTextBlockOverflow即使在尽最大努力将换行的文本框限制为特定的行数之后,我们也不得不期待随着时间的推移,我们会弄错,如果行数出于布局原因很重要,那么您可能会考虑修剪或截断文本甚至使用RichTextBlockOverflow

You can try this solution from How can I measure the Text Size in UWP Apps?您可以从How can I measure the Text Size in UWP Apps? 中尝试此解决方案? , and then validate against the height of the text, not specifically the number of lines. ,然后根据文本的高度进行验证,而不是具体的行数。

However I have in the past also found success by setting the TextBox to a fixed height (and of course width) and validated against the Scrollbar state.但是,我过去也通过将 TextBox 设置为固定高度(当然还有宽度)并针对滚动条 state 进行了验证,从而获得了成功。 Unfortunately it is hard to access the vertical scrollbar visibility directly, but we can use the ExtentHeight and the ViewportHeight on the ScrollViewer element that is inside the TextBox template.不幸的是,很难直接访问垂直滚动条的可见性,但我们可以在TextBox模板内的ScrollViewer元素上使用ExtentHeightViewportHeight

If the ExtentHeight is greater than the ViewportHeight then the scrollbar should be visible.如果ExtentHeight大于ViewportHeight ,那么滚动条应该是可见的。 If the Visual layout only allows the total number of lines that you want to support then the scrollbar should not ever be visible.如果可视布局只允许您想要支持的总行数,那么滚动条不应该是可见的。

Accessing the ScrollViewer gets interesting, options are discussed here How do access the scrollviewer of a TextBox in code访问ScrollViewer变得很有趣,这里讨论了选项How do access the scrollviewer of a TextBox in code

So try this as an adaptation to the solution from @10 Develops :因此,尝试将此作为对@10 Develops 解决方案的改编:

private void textBox_TextChanged(object sender, RoutedEventArgs e)
{
    var scroller = (sender as TextBox).FindChild<ScrollViewer>();
    if (scroller.ExtentHeight > scroller.ViewportHeight)
    {
        Debug.WriteLine("Limit reached");
        //your code here
    }
}

With this extension method defined in a static class:使用 static class 中定义的此扩展方法:
( using pattern matching, so a bit different to the original referenced post ) 使用模式匹配,所以与原来引用的帖子有点不同

public static T FindChild<T>(this DependencyObject parent) where T : UIElement
{
    if (parent is T matchedParent) return matchedParent;
    int children = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < children; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        if (child is T matchedChild)
            return matchedChild;
        else
        {
            T tChild = FindChild<T>(child);
            if (tChild != null) return tChild;
        }
    }
    return null;
}

I don't normally use this for validation of content, but I do use it to add buttons to toolbars that allow the user to quickly scroll to the top or bottom of the content and to toggle the visibility of such controls.我通常不使用它来验证内容,但我确实使用它来向工具栏添加按钮,允许用户快速滚动到内容的顶部或底部并切换此类控件的可见性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM