In my WPF style I have defined a standard grid row height I'd like to apply to several places like so:
<system:Double x:Key="TableRowHeight">22</system:Double>
However it does not work when I'd like to apply this like so:
<RowDefinition Height="{StaticResource TableRowHeight}"/>
Instead I need to create a complete style like:
<Style x:Key="GridTableRow" TargetType="{x:Type RowDefinition}">
<!--<Setter Property="Height" Value="{StaticResource TableRowHeight}"/>-->
<Setter Property="Height" Value="22"/>
</Style>
As can be seen from the commented out line trying to reference the numeric constant within the Style definition does not work either, but the "hardcoded" value does.
Now I've looked it up and I guess it is because the type associated with the Height property is GridLength and it somehow does not manage to automatically cast the double value when comming from another resource...
The problem is that there does not seem to be a way of creating a GridLength object from XAML. The Value propery is readonly. So something like this does not work either:
<Style x:Key="GridTableRow" TargetType="{x:Type RowDefinition}">
<Setter Property="Height">
<Setter.Value>
<GridLength Value="{StaticResource TableRowHeight}"/>
</Setter.Value>
</Setter>
</Style>
Is there a way to get this to work, or should I just forget using that constant and just use the RowDefinition style with the hardcoded value in place of the constant?
When you "hard code" values, the XAML processor looks up a converter that can convert it from string to the necessary type. Even your
TableRowHeight
resource is using DoubleConverter to be created.GridLength
uses GridLengthConverter.So there is no automatic cast / conversion happening in the compiler -- WPF needs to explicitly look up a class and call a convert method. In the case of
StaticResource
, it skips this step.Bindings do use type converters though, so the following would work as you expect:
This works because
GridLengthConverter
knows how to convert fromDouble
. In your case, this should not be necessary, though. If you initialize aGridLength
resource in the same way you initializedDouble
(inside the tags), the string conversion will be called before the resource is assigned:Then you would be able to call the resource directly.
you will have to create the resource of type
GridLength
in order to apply asRowDefinition.Height
is of typeGridLength
:This will work in anyway you want to apply it.
Try this: