【问题标题】:How to change the font size of a grid's children text blocks dynamically in c#?如何在 C# 中动态更改网格子文本块的字体大小?
【发布时间】:2015-07-17 19:42:04
【问题描述】:

在 Microsoft Visual Studio 中使用 c# 的 Windows Phone 8.1 WinRT 应用程序中,使用以下代码,如何在后面的代码中动态更改网格的子文本块的字体大小?

<Grid Name="mainGrid">

    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="5"/>
            <Setter Property="FontSize" Value="12"/>
        </Style>
    </Grid.Resources>

</Grid>

想法是让用户在选项屏幕中更改字体大小,然后将其保存到本地设置,然后更改显示以匹配字体大小。

加载应用程序时动态添加网格的子文本块,我不是在询问如何从 ApplicationData.Current.LocalSettings 加载值。我也知道样式和设置器还没有任何名称,如果需要可以填写。

如果可能,我想避免使用资源字典和数据绑定。

有人可以提供一个简单的代码示例,用于在后面的代码中更改字体大小吗?

【问题讨论】:

    标签: c# windows-runtime windows-phone


    【解决方案1】:

    这是我用来动态更改样式的方式,但会涉及到资源字典。

    private void changeSzie_Click(object sender, RoutedEventArgs e)
    {
        var dynamicStyle = new Windows.UI.Xaml.Style();
    
        var targetType = typeof(Windows.UI.Xaml.Controls.TextBlock);
    
        dynamicStyle.TargetType = targetType;
    
        dynamicStyle.Setters.Add(new Setter(Windows.UI.Xaml.Controls.TextBlock.FontSizeProperty, int.Parse(textbox.Text)));
    
        if (mainGrid.Resources.Keys.Contains(targetType))
        {
            mainGrid.Resources.Remove(targetType);
        }
    
        mainGrid.Resources.Add(targetType, dynamicStyle);
    }
    

    【讨论】:

    • 太好了,这行得通。我现在正在使用此代码: var style = new Style(typeof(TextBlock)); style.Setters.Add(new Setter(TextBlock.FontSizeProperty, 24)); mainGrid.Resources.Add(typeof(TextBlock), style);您能否提供一个设置 MarginProperty 的示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-09-10
    • 1970-01-01
    相关资源
    最近更新 更多