Мне нужно разработать Label
элемент управления в WPF , на .NET 3.5 и VisualStudio 2010 , в котором FontSize
автоматически выполнит текст заполняет область управления.
Я не знаю, должен ли я создать CustomControl
, унаследованный от Label
, или я должен создать UserControl
, который содержит элемент управления Label
.
Я видел здесь пример использования ValueConverter
, но я не понимаю его поведение, здесь: динамическое изменение размера шрифта .
Может кто-нибудь подсказать мне об этом?
Обновление:
Я нашел решение, используя DoubleConverter
из приведенного выше примера:
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 необходимо создать экземпляр 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
полностью зависит от назначенного шрифта. Каждый шрифт может нуждаться в различном значении, и вам нужно «поиграть», чтобы получить правильное значение для точного соответствия.