如何从我的Helper类将字体绑定到我的DataGridHeader

时间:2017-03-22 12:39:16

标签: c# wpf fonts binding

如何将字体绑定到我的Helper类中的DataGridHeader,这个类叫做Globals,它是公共静态的,如下所示:

public static class Globals
{
    public static int DataGridfontSizeHeader { get; set; }
    public static int DataGridfontSizeContent { get; set; }
}

在这个课程中,我持有FontSize的值。

现在我想将此类中的值应用于我的DataGrid列标题和DataGrid内容(行和列中显示的数据的字体大小)

我尝试了类似这样的标题:

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="SeparatorBrush" Value="Yellow" />
    <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 MyProject.Helpers.Globals.DataGridfontSizeHeader }"/>
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="Height" Value="40"/>
    <Setter Property="Padding" Value="0,0,17,0"/>
    <!--Margin to shift the entire header to the right 17 units to fill the void-->
    <Setter Property="Margin" Value="0,0,-17,0"/>
</Style>

但不幸的是它没有用,

所以我的问题是如何将此Global类中的字体应用到我的DataGrid内容和DataGrid标题列?

谢谢你们, 干杯

2 个答案:

答案 0 :(得分:1)

将属性类型更改为double,并将有效字体大小指定为默认值:

public static class Globals
{
    public static double DataGridfontSizeHeader { get; set; } = 10;
    public static double DataGridfontSizeContent { get; set; } = 10;
}

然后你可以在Style中设置属性的值,如下所示:

<Setter Property="FontSize" Value="{x:Static local:Globals.DataGridfontSizeHeader}"/>

&#34;本地&#34;是映射到定义类的CLR命名空间的命名空间:

<Window x:Class="WpfApplication3.Window23"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    ...

修改

  

是的,自C#6.0起包含了自动属性初始值设定项的能力,不幸的是我使用C#5.0,因为你可以看到我的类是静态的,所以我不能在构造函数中定义它,因为静态类不能有一个构造函数,hmmmmm

只需定义一个static构造函数:

public static class Globals
{
    static Globals()
    {
        DataGridfontSizeHeader = 10;
        DataGridfontSizeContent = 10;
    }

    public static double DataGridfontSizeHeader { get; set; }
    public static double DataGridfontSizeContent { get; set; }
}

答案 1 :(得分:0)

首先,您尝试将类的int属性绑定到double FontSize属性(它会抛出异常)。

其次,虽然你可以选择&#34; bind&#34;静态属性(参见@mm8回答)它只是一次绑定,因为INotifyPropertyChanged仅对实例有意义。因此,您在运行时对静态属性所做的更改不会被反映出来。

这里的解决方案是使用单例模式。