Label
控制
,开
.NET 3.5版
VisualStudio 2010年
,其中
FontSize
将自动使文本填充控制区域。
我不知道我是否应该创建一个
CustomControl
继承自
标签
UserControl
包含一个
标签
控制。
我在这里看到了一个使用
ValueConverter
change font size dynamically
.
有人能给我一个线索吗?
我找到了解决办法
DoubleConverter
灵魂正在使用
值转换器
,但添加了numeriformat formatprovider以正确解析“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();
}
}
双转换器
,并在
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
完全取决于指定的字体。每种字体可能需要一个不同的值,你必须“到处玩”,以获得正确的值,以准确地适应。