我需要开发Label
控制WPF,在.NET 3.5和的VisualStudio 2010,其中FontSize
会自动使文本填满控制区。WPF标签适应字号它的宽度和高度
我不知道我是否应该建立一个CustomControl
从Label
继承或者我应该创建一个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
值从指定的字体绝对依赖。每种字体都可能需要不同的值,您必须“四处游玩”才能得到正确的值。
嗯,我终于放弃这种方式并用: 很简单,有效。 –
JoanComasFdz
2010-07-14 09:28:56
您应该添加解决方案作为答案并将其标记为正确。 – 2011-09-01 16:08:20