使用 C# 变量设置 XAML 属性

K4L*_*L3L 0 c# wpf xaml

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

“ArgumentException:“Verdana”不是属性“FontFamily”的有效值。

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

我使用了以下代码:

C# 类

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

Run Code Online (Sandbox Code Playgroud)

XML命名空间

xmlns:local="clr-namespace:Ueb21d_SplitPanel;assembly=Ueb21d_SplitPanel"
Run Code Online (Sandbox Code Playgroud)

一键式 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}"/>
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 5

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

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;
}
Run Code Online (Sandbox Code Playgroud)