WPF GridLength in XAML

3.8k views Asked by At

I'm trying to define a common Width resource in Common.xaml which will be shared by different controls, like following:

<GridLength x:Key="CommonWidth">20</GridLength>

I then use it in a Button style defined in ButtonStyle.xaml

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Width" Value="{DynamicResource CommonWidth}"/>
    ....
</Style>

Common.xaml is included before ButtonStyle.xaml in the ResourceDictionary definition in App.xaml. When I ran the application (on .Net3.5 SP1), I got the following exception:

'20' is not a valid value for property 'Width'.

Anyone has any ideas of what I have done wrong? Thanks in advance.

2

There are 2 answers

0
Klaus78 On BEST ANSWER

Note that Button.Width is not of type GridLength. In Grid.GridLength you can specify the value as fixed, auto or star. It is only used for size of rows, columns in Grid.

Button.Width is of type double. That is if you want to set it using a resource you need a resource like

<sys:Double x:Key="Height">200</sys:Double>
0
JUNAID MUSLA On

For any of the control, having width of type double you can assign the value via StaticResource as below:

Namespace to include in your xaml file:

xmlns:system="clr-namespace:System;assembly=System.Runtime"

Defining height and width as resources:

<ResourceDictionary>
    <system:Double x:Key="ControlWidth">200</system:Double>
    <system:Double x:Key="ControlHeight">20</system:Double>
</ResourceDictionary>

Assigning value to a control:

<TextBox x:Name="TextBox" Width="{StaticResource ControlWidth}" Height="{StaticResource ControlHeight}"/>