Set button Height from a constant value defined in a class in WPF

36 views Asked by At

I have an issue while trying to set the height of all my app buttons to a constant value. My project has many Windows and controls, and a requirement is all controls to have the same height in pixels, so I'd prefer to have that value storaged in a constant.

I have isolated the problem in a new project and getting the same error, the code is very simple. Let's say I have a class like this, with a namespace defined and a const string value:

namespace WpfApp.MyDesigner
{
    public class MyStyles
    {
        public const string NavigationBarHeight = "64";
    }
}

Then my app just open this .xaml view defined as a default Window with a Button on a Grid:

<Window x:Class="WpfApp.Views.WindowWithButton"
        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:constants="clr-namespace:WpfApp.MyDesigner"
        mc:Ignorable="d"
        Title="WindowWithButton" Height="450" Width="800">
    <Grid>
        <Button Width="{x:Static constants:MyStyles.NavigationBarHeight}" Height="64"></Button>
    </Grid>
</Window>

Notice that I'm just trying to set the Width (or the Height, the error is the same) as the constant value defined on my before class, whose value is "64".

The namespace is added with:

xmlns:constants="clr-namespace:WpfApp.MyDesigner"

And the const is correctly referenced in the Button definition with:

<Button Width="{x:Static constants:MyStyles.NavigationBarHeight}" Height="64"></Button>

But I get a runtime error specifying the value "64" is not valid for the Width property

enter image description here

I have tried to define the const as integer and deleting /bin and /obj folders before compiling, also trying with empty new projects, changing namespaces, class names... but error is always the same, I can't get that const value from my .xaml and I'm totally stuck with this part.

2

There are 2 answers

1
XeRiCZ On BEST ANSWER

Width property is defined in System.Windows.FrameworkElement as:

public double Width { get; set; }

so your constant should be

public const double NavigationBarHeight = 64;

instead of string.

1
ASh On

if you are stuck with a string constant for some reason (e.g. it comes from 3rd party library), you can still use it by creating a Binding, which will take care of type convertion:

Height="{Binding Source={x:Static constants:MyStyles.NavigationBarHeight}}"