c# - 如何知道文本是否大于文本框?

标签 c# wpf

有没有办法知道我在 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/

相关文章:

c# - 如何确定文件最近一次重命名的时间?

c# - 我怎样才能成为更好的 WPF 开发人员?

c# - 修改 FormAuthentication 302 重定向行为

c# - 使用 Roslyn RC 发送到 DynamicAssembly

c# - 如何在任意网格上找到顶点的邻居?

C#动态复选框创建

c# - 如何在 XAML 和 C# 中将字符串列表显示为 DataGrid(表)

wpf - Powershell 中的自定义 XAML 命名空间

c# - 如何在 App.Config 中设置相对路径?

c# - 如何获取 DependencyProperty 的默认值