Roxy'Pro
Roxy'Pro

Reputation: 4444

How to set DataGrid Header's font size programatically from code behind

I'm wondering how could I set my DataGrid Header Font size programatically, in case I would like to keep my font size in the database, because sometimes user might move aplication to a smaller monitor(1024x768) let's say and that simply he might edit his font size and everything is gonna be fine.

This is Style I am using right now to style my header:

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Background" Value="#0091EA"/>
    <Setter Property="Opacity" Value="1"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="FontSize" Value="16"/>
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="Height" Value="40"/>
</Style>

So how could I set this properties from code behind if I would like to

Could I do simply smth like this:

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Background" Value="#0091EA"/>
    <Setter Property="Opacity" Value="1"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="FontSize" Value="{Binding FontSize}"/>
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="Height" Value="40"/>
</Style>

I changed <Setter Property="FontSize" Value="16"/>

to

<Setter Property="FontSize" Value="{Binding FontSize}"/>

Value="{Binding FontSize}" //is new

so how can I add value to this FontSize to be something from my code behind?

Upvotes: 0

Views: 1054

Answers (1)

mm8
mm8

Reputation: 169220

You could for example add a double property to your window:

public partial class MainWindow : Window
{
    public double MyFontSize { get; set; } = 30;

    public MainWindow()
    {
        InitializeComponent();
    }
}

<Window.Resources>
    <Style TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="Background" Value="#0091EA"/>
        <Setter Property="Opacity" Value="1"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="FontSize" Value="{Binding MyFontSize, RelativeSource={RelativeSource AncestorType=Window}}"/>
        <Setter Property="FontFamily" Value="Arial"/>
        <Setter Property="Height" Value="40"/>
    </Style
</Window.Resources>

Note that if you want to be able to change the value of the source property dynamically at runtime, the window class (or wherever you choose to implement the property) should implement the INotifyPropertyChanged event and raise change notifications.

Upvotes: 1

Related Questions