Joa*_*Fdz 9 wpf label font-size width
我需要在.NET 3.5和VisualStudio 2010上开发WPF中的Label控件,其中将自动使文本填充控制区域.FontSize
我不知道是否应该创建一个CustomControl继承,Label或者我是否应该创建一个UserControl包含Label控件的.
我在这里看到一个使用a的例子ValueConverter,但我不理解它的行为,这里:动态改变字体大小.
任何人都可以给我一个线索吗?
更新:
我使用DoubleConverter之前发布的示例找到了解决方案:
灵魂使用a 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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您必须在XAML中实例化DoubleConverter,并在FonSizeProperty中指定绑定:
<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>
Run Code Online (Sandbox Code Playgroud)
An important point is that the value for ConverterParameter depends absolutely from the font assigned. Each font may need a different value and you have to "play around" to get the correct value to fit exactly.
Ale*_*ker 27
<Viewbox>
<TextBlock>asd</TextBlock>
</Viewbox>
Run Code Online (Sandbox Code Playgroud)
这项工作也是如此.