How to change the font size of a grid's children text blocks dynamically in c#?

落花浮王杯 提交于 2019-12-08 08:04:07

问题


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:


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);
}


来源:https://stackoverflow.com/questions/31483538/how-to-change-the-font-size-of-a-grids-children-text-blocks-dynamically-in-c

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