How to change the font size of a grid's childr

2019-05-30 10:19发布

In a Windows Phone 8.1 WinRT app using c# in Microsoft Visual Studio, with the following code, how can I change the font size of the grid's children text blocks dynamically in the code behind?

<Grid Name="mainGrid">

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

</Grid>

The idea is to let the user change the font size in the options screen, and then save it to local settings, and then change the display to match the font size.

The grid's children text blocks are added dynamically when the app is loaded, and I'm not asking how to load values from ApplicationData.Current.LocalSettings. I'm also aware that the styles and setters don't have any names yet, which could be filled in if needed.

I would like to avoid using a resource dictionary and data bindings if possible.

Can someone provide a simple code example to use in the code behind to change the font size?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-30 10:44

Here is the way I used to change the style dynamically, but the resource dictionary would be involved.

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);
}
查看更多
登录 后发表回答