WPF标签如何根据宽度和高度自适应字体大小

11
我需要在WPF上开发一个标签控件,在.NET 3.5和VisualStudio 2010上,使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,并在FontSize属性中指定绑定:

<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 的值绝对取决于所分配的字体。每种字体可能需要不同的值,您需要“尝试”以获得完全匹配的正确值。


1
好吧,我最终放弃了之前的方法,改用:<Viewblock> <TextBlock/> <ViewBlock> 非常简单而且有效。 - JoanComasFdz
1
你应该将你的解决方案添加为答案并将其标记为正确。 - Jack B Nimble
1个回答

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

同样也能完成工作。


1
不要忘记,您还可以使用StretchDirection属性,仅在内容无法适应时才将其缩小...但当内容适应时,请将其保持不变。 - cplotts
1
虽然viewbox技巧可以起到作用,但它也会调整已经渲染的文本大小,这可能导致文本不如实际渲染到适当大小时那么清晰。 - reuscam
2
@reuscam:我认为这不是viewbox的工作方式。它不会调整已经渲染好的内容,而是应用在内容渲染时使用的变换。至少我希望是这样,因为这是WPF渲染概念的一部分。 - Alex Maker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接