【发布时间】: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。这两种方法都用于以像素为单位测量字符串长度。