如何将TextBlock的字体大小设置为另一个字体大小属性的比率?

时间:2018-08-15 18:17:21

标签: c# wpf xaml

我在自定义用户控件中有一个TextBlock,我希望它比该用户控件的全局字体大小属性稍大一些(也许大7%)。我不确定执行此操作的最佳方法。有人有建议吗?

(显然,这种尝试是很残酷的,但是希望它可以使我的要求形象化)。

$stmt->errno

3 个答案:

答案 0 :(得分:1)

最好的答案(贷记为@Kenny)是一个简单的转换器,它接受用户控制的字体大小作为输入。

在xaml中使用:

<z:RatioConverter x:Key="AdjustTitleFontSizeConverter" Ratio="1.07" />

<TextBlock 
    x:Name="Title" 
    FontSize="{Binding FontSize, Converter={StaticResource AdjustTitleFontSizeConverter}"> 
    Hello Custom User Control! 
</TextBlock>

RatioConverter.cs

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

public class RatioConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Input santize first..
        return (System.Convert.ToDouble(value)) * this.Ratio;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public Double Ratio
    {
        get { return (Double)GetValue(RatioProperty); }
        set { SetValue(RatioProperty, value); }
    }

    public static readonly DependencyProperty RatioProperty = DependencyProperty.Register(
        "Ratio", typeof(Double), typeof(RatioConverter), new FrameworkPropertyMetadata(1.0));
}

答案 1 :(得分:1)

以所需的比例因子应用ScaleTransform

在此示例中,所有TextBlock均从父窗口继承FontSize = 20(这是“依赖项属性”继承)。然后,将一个TextBlock的FontSize更改为22,然后缩放另一个(20 * 1.1 == 22)。他们看起来和我相似。

<Window x:Class="WpfDemos.FontWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WpfDemos" Height="300" Width="300" FontSize="20">
    <StackPanel>
        <TextBlock Text="Hello Custom User Control!"/>
        <TextBlock Text="Hello Custom User Control!"/>

        <TextBlock Text="Hello Custom User Control!">
            <TextBlock.LayoutTransform>
                <ScaleTransform ScaleX="1.1" ScaleY="1.1"/>
            </TextBlock.LayoutTransform>
        </TextBlock>

        <TextBlock Text="Hello Custom User Control!" FontSize="22"/>

        <TextBlock Text="Hello Custom User Control!"/>
        <TextBlock Text="Hello Custom User Control!"/>
    </StackPanel>
</Window>

答案 2 :(得分:0)

您可以为此使用https://www.nuget.org/packages/CalcBinding/库。

相关问题