【发布时间】:2011-03-14 20:20:27
【问题描述】:
我需要在 .NET 3.5 和 VisualStudio 2010 上的 WPF 中开发一个Label 控件,其中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,并在 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 的值绝对取决于分配的字体。每种字体可能需要不同的值,您必须“玩弄”才能获得正确的值以完全适合。
【问题讨论】:
-
好吧,我终于放弃了这种方式并使用了:
相当简单有效。 -
您应该将您的解决方案添加为答案并将其标记为正确。