WPF自定义控件模板-相对字体大小 [英] Wpf custom control template - relative font size

查看:211
本文介绍了WPF自定义控件模板-相对字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个自定义WPF控件,为了简单起见,它具有一个带有标题 TextBlock的垂直堆栈面板,后跟一个ContentPresenter。我希望标题的字体大小比内容中使用的大小大5点,这是由用户将控件放置在其中的任何容器继承的。

I am creating a custom WPF control that let's say for simplicity sake has a vertical stack panel with a "title" TextBlock, followed by a ContentPresenter. I want the font size for the "title" to be 5 Points LARGER than the size used in the content, which is inherited by whatever container the user places this control in.

如何在控件模板中使用相对值为标题元素指定字体大小,而又不向用户公开 TitleFontSize之类的属性?我想做加5。

How can I specify a font size in the control template for the header element using a relative value without exposing a property like "TitleFontSize" to the user? I want do "add 5".

我尝试在标头文本块上使用ScaleTransform混合结果(文本块可以缩放,但是方向已修改-我有文本右对齐,并且缩放后将其移出控件区域)。另外,我不确定比例转换是否在这里合适。

I tried using a ScaleTransform on the header text block with mixed results (the text block scaled fine but the orientation was modified - I had the text right-justified and it moved "off the control" area when scaled). Also, I am not sure if scale transform would be approprite here.

推荐答案

我使用IValueConverter进行了如下操作:

I did it with an IValueConverter as follows:

已创建从IValueConverter派生的FontSizeConverter类。 Convert方法的值加10,而ConvertBack方法的值减10。

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
}

下一步,我在控件的XAML模板中声明了此类的实例:

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

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

Finnaly,FontSize绑定使用此转换器应用于继承的FontSize属性:

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.

这篇关于WPF自定义控件模板-相对字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆