我需要开发一个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/