2010-07-12 92 views
9

我需要开发Label控制WPF,在.NET 3.5的VisualStudio 2010,其中FontSize会自动使文本填满控制区。WPF标签适应字号它的宽度和高度

我不知道我是否应该建立一个CustomControlLabel继承或者我应该创建一个UserControl含有Label控制。

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

任何人都可以给我一个线索吗?

更新:

我发现使用来自例如DoubleConverter我已经发布前solutiion:本soultion使用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的实例,并指定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值从指定的字体绝对依赖。每种字体都可能需要不同的值,您必须“四处游玩”才能得到正确的值。

+1

嗯,我终于放弃这种方式并用: 很简单,有效。 – JoanComasFdz 2010-07-14 09:28:56

+1

您应该添加解决方案作为答案并将其标记为正确。 – 2011-09-01 16:08:20

回答

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

也做这项工作。

+1

不要忘记,您还可以使用StretchDirection在不适合的时候调整大小,但在适合时保持不变。 – cplotts 2012-03-09 18:00:11

+0

虽然视框技巧有效,但它也调整了已经呈现的文本的大小,这可能不像实际渲染到适当大小那样清晰。 – reuscam 2013-05-09 16:43:05

+2

@reuscam:我不认为这是视框的工作方式。它不调整已经呈现的内容的大小,它应用了呈现内容时使用的转换。至少我希望这样做,因为它是WPF渲染概念的一部分。 – 2013-07-24 10:25:35