LORD Asked:2020-07-04 22:29:32 +0000 UTC2020-07-04 22:29:32 +0000 UTC 2020-07-04 22:29:32 +0000 UTC 如果文本不适合 TextBox WPF,如何使字体变小 772 如果文本不适合该字段,如何对其进行“压缩”。 假设我有一个输入全名的TextBox,它不能传输,所以你需要确保用大文本,字体减小 c# 1 个回答 Voted Best Answer Андрей NOP 2020-07-05T16:02:22Z2020-07-05T16:02:22Z 为了不损坏控件本身并仅更改其中的字体大小,您可以编写一个简单的转换器: class AdaptiveFontSizeConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var textBox = (TextBox)values[0]; var dpiX = 96.0 * VisualTreeHelper.GetDpi(textBox).DpiScaleX; // .NET 4.6.2+ var formattedText = new FormattedText( textBox.Text, CultureInfo.InvariantCulture, textBox.FlowDirection, new Typeface( textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch), textBox.FontSize, textBox.Foreground, dpiX); var fontSize = textBox.FontSize * textBox.ViewportWidth / formattedText.Width; if (parameter == null) return fontSize; var maxSize = (double)parameter; return Math.Min(fontSize, maxSize); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotSupportedException(); } 我们用: <Grid Margin="5" xmlns:s="clr-namespace:System;assembly=mscorlib"> <Grid.Resources> <c:AdaptiveFontSizeConverter x:Key="conv"/> </Grid.Resources> <TextBox VerticalAlignment="Top"> <TextBox.FontSize> <MultiBinding Converter="{StaticResource conv}"> <MultiBinding.ConverterParameter> <s:Double>12</s:Double> </MultiBinding.ConverterParameter> <Binding RelativeSource="{RelativeSource Self}"/> <Binding Path="Text" RelativeSource="{RelativeSource Self}"/> </MultiBinding> </TextBox.FontSize> </TextBox> </Grid> 事实上,转换器本身只接受到 TextBox 的链接,但由于 我们需要响应其中文本的变化,然后我们制作一个多转换器并将对 Text 属性的引用作为第二个对象传递(但第二个对象在代码中没有使用)。然后一切都很简单——我们测量控件内文本的宽度并计算最终的字体大小。好吧,我添加了将最大字体大小指定为参数的功能,这样当控件中的字符很少时,控件就不会变得非常大。
为了不损坏控件本身并仅更改其中的字体大小,您可以编写一个简单的转换器:
我们用:
事实上,转换器本身只接受到 TextBox 的链接,但由于 我们需要响应其中文本的变化,然后我们制作一个多转换器并将对 Text 属性的引用作为第二个对象传递(但第二个对象在代码中没有使用)。然后一切都很简单——我们测量控件内文本的宽度并计算最终的字体大小。好吧,我添加了将最大字体大小指定为参数的功能,这样当控件中的字符很少时,控件就不会变得非常大。