我需要在WPF上开发一个标签控件,在.NET 3.5和VisualStudio 2010上,使
FontSize
自动调整以填充控件区域。我不知道是应该创建继承Label
的CustomControl
还是创建包含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
的值绝对取决于所分配的字体。每种字体可能需要不同的值,您需要“尝试”以获得完全匹配的正确值。