【问题标题】:How to delete last entering character(s) if TextBox width bigger than 75如果 TextBox 宽度大于 75,如何删除最后输入的字符
【发布时间】:2019-03-17 00:30:55
【问题描述】:

1- 将以下代码复制并粘贴到 MainWindow.xaml 文件中。

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox x:Name="TextBox1" Height="25" HorizontalAlignment="Left" Text="Hello people"/>
    <Label x:Name="LabelForTestingNeeds1" Height="25" HorizontalAlignment="Left" Margin="0,100,0,0" Content="{Binding ActualWidth, ElementName=TextBox1}"/>
    <Label x:Name="LabelForTestingNeeds2" Height="25" HorizontalAlignment="Left" Margin="0,150,0,0" Content="{Binding Text.Length, ElementName=TextBox1}"/>
</Grid>
</Window>

2- 将以下代码复制并粘贴到 code behind 文件中。

Class MainWindow
    Private Sub TextBox1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles TextBox1.TextChanged
        If TextBox1.ActualWidth > 75 Then
            'Delete last entering character(s)
            'Or prevent entering a new character(s)
        End If
    End Sub
End Class

3- 运行这个项目并将一些字符添加到 TextBox1 中。

如果 TextBox1 宽度大于 75,如何删除最后输入的字符?

如果 TextBox1 的宽度大于 75,如何防止在 TextBox1 中输入字符?

所以这个问题是关于以像素为单位的文本框宽度。

【问题讨论】:

  • 你的意思是限制可以输入的最大字符数还是控件的最大宽度?我认为您指的是字符数。反正TextBox控件有MaxLength、MaxWidth、MaxHeight、MaxLines属性,其中MaxLength是控件可以接受的最大字符数。
  • @Jimi 我已经尝试使用 MaxLength 属性,但 MaxLength 属性对我来说并不合适。例如Jimi 由 4 个字符组成,Dann 由 4 个字符组成。但是Jimi 长度和Dann 长度不相等。因为字母表中的每个字符都有不同的宽度。w 是最宽的字符,i 是最窄的字符。
  • 啊,你的意思是文本长度(以像素为单位)吗? FormattedText 可用于测量字符串长度(以像素为单位)。或TextRenderer.Measuretext。这取决于您更舒适的方法。如果字符串长度大于某个值,您可以测量字符串并删除最后输入的字符。
  • 是的,我的意思是以像素为单位的文本长度。
  • 查看答案here。这两种方法都用于以像素为单位测量字符串长度。

标签: c# wpf vb.net


【解决方案1】:

这是文本更改事件,因此您无法阻止输入字符,但这应该可以工作

Class MainWindow
    Private Sub TextBox1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles TextBox1.TextChanged
        If TextBox1.Text.length > 75 Then
            TextBox1.Text = TextBox1.Text.Substring(0, 75)
        End If
    End Sub
End Class

【讨论】:

  • 你的答案不正确,因为字母表中的每个字符都有不同的宽度。w 是最宽的字符,i 是最窄的字符。
  • Length != width 长度是字符数
【解决方案2】:

绘制文本的大小不仅取决于您评论时使用的字符,还取决于字体类型和字体大小。

有一个专门用于计算这个的类,即System.Windows.Media 命名空间中的FormattedText

只需创建一个新对象,其中包含有关要绘制的文本、其字体和其他属性的信息:

var formattedText = new System.Windows.Media.FormattedText("my text", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("MyFont"), 32, Brushes.Black);
var width = formattedText.Width; //use to limit or do whatever

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多