使用 C# 变量设置 XAML 属性

Using C# variable to set XAML attributes

我一直在尝试使用 C# 变量来设置 XAML 属性的值,但没有成功。我有一个保存值 "Verdana" 的变量,这是我想在应用程序按钮上使用的字体,但是在尝试编译代码时出现异常:

"ArgumentException: "Verdana" is not a valid value for the attribute "FontFamily".

除了宽度和高度之外,每个具有来自变量的值的属性都会出现相同的异常。我很感激任何关于如何解决这个问题的建议。

我使用了以下代码:

C#Class

namespace Ueb21d_SplitPanel
{
    public static class AzoConst
    {
        public static readonly double FONTSIZE_BUTTON = 16;
        public static readonly string BACKGROUND_BUTTON = "Green";
        public static readonly string FONT_BUTTON = "Verdana";
        public static readonly string FONTCOLOR_BUTTON = "White";
        public static readonly double WIDTH_BUTTON = 70;
        public static readonly double HEIGHT_BUTTON = 30;
    }
}

XML 命名空间

xmlns:local="clr-namespace:Ueb21d_SplitPanel;assembly=Ueb21d_SplitPanel"

XAML 一个按钮的代码

<Button x:Name="btnClose" Content="Close" 
        Width="{x:Static local:AzoConst.WIDTH_BUTTON}"
        Height="{x:Static local:AzoConst.HEIGHT_BUTTON}" Margin="5,0,0,0"
        IsCancel="True" RenderTransformOrigin="0.5,0.5" 
        FontFamily="{x:Static local:AzoConst.FONT_BUTTON}"
        Foreground="{x:Static local:AzoConst.FONTCOLOR_BUTTON}"
        Background="{x:Static local:AzoConst.BACKGROUND_BUTTON}"
        FontSize="{x:Static local:AzoConst.FONTSIZE_BUTTON}"/>

使用与依赖属性类型相匹配的适当类型,它将起作用。

public static class AzoConst
{
   public static readonly double FONTSIZE_BUTTON = 16;
   public static readonly Brush BACKGROUND_BUTTON = Brushes.Green;
   public static readonly FontFamily FONT_BUTTON = new FontFamily("Verdana");
   public static readonly Brush FONTCOLOR_BUTTON = Brushes.White;
   public static readonly double WIDTH_BUTTON = 70;
   public static readonly double HEIGHT_BUTTON = 30;
}