【问题标题】:WPF Label adapt FontSize to it's Width and HeightWPF 标签使 FontSize 适应它的宽度和高度
【发布时间】:2011-03-14 20:20:27
【问题描述】:

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

我不知道是应该创建一个继承自 LabelCustomControl,还是应该创建一个包含 Label 控件的 UserControl

我在这里看到了一个使用 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 属性中指定绑定:

<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 的值绝对取决于分配的字体。每种字体可能需要不同的值,您必须“玩弄”才能获得正确的值以完全适合。

【问题讨论】:

  • 好吧,我终于放弃了这种方式并使用了: 相当简单有效。
  • 您应该将您的解决方案添加为答案并将其标记为正确。

标签: wpf label width font-size


【解决方案1】:
<Viewbox>
    <TextBlock>asd</TextBlock>
</Viewbox>

也能胜任。

【讨论】:

  • 不要忘记,您也可以使用 StretchDirection 仅在不适合时调整大小……但在适合时不理会它。
  • 虽然 viewbox 技巧有效,但它也会调整已渲染文本的大小,这可能不像实际渲染到适当大小那样清晰。
  • @reuscam:我不认为这是视图框的工作方式。它不会调整已渲染内容的大小,它会应用渲染内容时使用的转换。至少我希望它这样做,因为它是 WPF 渲染概念的一部分。
猜你喜欢
  • 1970-01-01
  • 2023-01-03
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 2018-09-11
  • 2021-07-31
  • 1970-01-01
相关资源
最近更新 更多