WPF 标签使 FontSize 适应它的宽度和高度

标签 wpf label width font-size

我需要开发一个Label控制在 WPF , 在 .NET 3.5 Visual Studio 2010 ,其中FontSize将自动使文本填充控制区域。

我不知道我是否应该创建一个 CustomControl继承自 Label或者如果我应该创建一个 UserControl其中包含 Label控制。

我在这里看到了一个使用 ValueConverter 的示例,但我不理解它的行为,这里:change font size dynamically .

谁能给我一个线索?

更新:

我使用 DoubleConverter 找到了解决方案从我之前发布的示例中:

灵魂正在使用 ValueConverter ,我从示例中提取,但添加了 NumerFormat IFormatProvider 以正确解析“0.1”值,我发现在 Decimal d1 = Decimal.Parse("0.1"); // = 1?!? :

 [ValueConversion(typeof(object), typeof(double))]
 public class DoubleConverter : IValueConverter
 {
  public object Convert(object value, Type targetType,
   object parameter, CultureInfo culture)
  {
   double dblValue = (double)value;
   double scale = Double.Parse(((string)parameter), System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
   return dblValue * scale;
  }

  public object ConvertBack(object value, Type targetType,
   object parameter, CultureInfo culture)
  {
   throw new NotImplementedException();
  }
 }

然后,您必须在 XAML 中实例化 DoubleConverter ,并在 FonSize 中指定绑定(bind)属性(property):
<UserControl x:Class="<Namespace>.LabelAutoFontSize"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:me="clr-namespace:<Namespace>"
  mc:Ignorable="d" 
  d:DesignHeight="60" d:DesignWidth="278">
 <UserControl.Resources>
 <me:DoubleConverter x:Key="doubleConverter" />
 </UserControl.Resources>
 <Grid>
 <Label
  x:Name="lbl"
  FontSize="{
   Binding Path=Width,
    RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
   Converter={StaticResource doubleConverter},
   ConverterParameter=0.116}"

  VerticalAlignment="Stretch"
  HorizontalAlignment="Stretch"
  Content="LabelAutoFontSize"
  d:LayoutOverrides="Width"
  HorizontalContentAlignment="Center"
  VerticalContentAlignment="Center" />
 </Grid>
</UserControl>

重要的一点是 ConverterParameter 的值绝对取决于分配的字体。每种字体可能需要不同的值,您必须“玩弄”才能获得正确的值以完全适合。

最佳答案

<Viewbox>
    <TextBlock>asd</TextBlock>
</Viewbox>

也做这项工作。

关于WPF 标签使 FontSize 适应它的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3229337/

相关文章:

c# - 在不同行显示不同标签

html - CSS 边框宽度改变布局

html - 如何正确创建 div 之间的偏移量

wpf - Caliburn.Micro 和自定义依赖属性不起作用

WPF 覆盖 ContextMenu 样式 - DropShadowEffect 不起作用

r - 如何使用ggplot2修改multiple-ggproto中标签的背景颜色

iphone - UIImage size.width 返回高度?

wpf - 取消在 DataGrid 中添加新行

c# - WPF Datagrid 单元格、cellinfo 和 selectedcells + 自定义选择

highcharts - "1"的步进间隔在 Highcharts 中对我不起作用,为什么?