有没有办法知道我在 wpf 文本框中的文本是否超出了它的长度?
注意:我说的是像素长度,而不是最大长度的字符长度
基本上,如果文本框是 50 像素长。 我在里面有一段文字是: “Supercalifragilisticexpialidocious!尽管它的声音非常糟糕”
那它放不下对吧?我想知道它不适合它。 但是如果文本框是 900 像素宽。它只是可能。
我目前正在检查类似以下内容。
private double GetWidthOfText()
{
FormattedText formattedText = new FormattedText(MyTextbox.Text,
System.Globalization.CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight, new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal), MyTextbox.FontSize, Brushes.Black);
return formattedText.Width;
}
...
if (textBox.Width < GetWidthOfText()) ...
但我发现它非常笨拙,而且从来没有真正起作用。我试图找到更可靠的东西。有什么想法吗?
最佳答案
您可以继承文本框,然后创建一个自定义方法来返回您想要的值:
public class MyTextBox :TextBox
{
public bool ContentsBiggerThanTextBox()
{
Typeface typeface = new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch);
FormattedText ft = new FormattedText(this.Text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, this.FontSize, Brushes.Black);
if (ft.Width > this.ActualWidth)
return true;
return false;
}
}
您在 XAML 中将文本框声明为 MyTextBox 而不是 TextBox,然后您可以简单地执行以下操作:
private void button1_Click(object sender, RoutedEventArgs e)
{
if (tb.ContentsBiggerThanTextBox())
MessageBox.Show("The contents are bigger than the box");
}
关于c# - 如何知道文本是否大于文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900892/