Wpf custom control template - relative font size

和自甴很熟 提交于 2019-11-29 07:22:05

A more generic way

Value converter

public class MathConverter : IValueConverter
{
    public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
    {
        return (double)value + double.Parse( parameter.ToString() );
    }

    public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
    {
        return null;
    }
}

Converter Resource

<my:MathConverter x:Key="MathConverter" />

XAML

<TextBlock FontSize="{Binding
                     RelativeSource={RelativeSource AncestorType={x:Type Window}},
                     Path=FontSize,
                     Converter={StaticResource MathConverter},
                     ConverterParameter=2}" />

I did it with an IValueConverter as follows:

Created a class FontSizeConverter that derives from IValueConverter. The Convert method adds 10 to the value, and the ConvertBack method subtracts 10.

public class FontSizeConverter : IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)value + 12.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)value - 12.0;
    }

    #endregion
}

Next, I declaried an instance of this class in the XAML template for the control:

<Style.Resources>
        <local:FontSizeConverter x:Key="fontSizeConverter"/>
</Style.Resources>

And Finnaly, the FontSize binding uses this converter applied to the inherited FontSize property:

<TextBlock FontSize="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=FontSize, Converter={StaticResource fontSizeConverter}}" 
                                   Grid.Row="0" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                                   Path=Date.Day}" HorizontalAlignment="Right" VerticalAlignment="Top" Padding="2" Margin="2" >
 </TextBlock>

This works. But I still do not know if this is the correct answer. Let me know if there is a better way, or if this is appropriate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!