Home > database >  Using C# variable to set XAML attributes
Using C# variable to set XAML attributes

Time:02-21

I have been trying to use C# variables to set the values of XAML attributes, but haven't had success. I have a variable holding the value "Verdana", the font I'd like to use on the buttons of the application, however when trying to compile the code I get an exception:

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

The same exception appears for every attribute with a value coming from a variable, besides width and height. I'm grateful for any suggestions on how to solve this.

I used the following code:

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 Namespace

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

XAML code for one button

<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}"/>

CodePudding user response:

Use the appropriate types that match the types of the dependency properties and it will work.

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