Assign static value to GridLength resource

1.1k views Asked by At

Case

I've defined a series of GridLenghts as a resource in my WPF Window:

<w:GridLength x:Key="ScrollBarRowHeight">17</w:GridLength>

Since this scrollbar height is variable dependent on the operating system used, I'd like to refactor this line of code to use the static parameter value SystemParameters.HorizontalScrollBarHeight.

Problem

I've tried both these lines:

<w:GridLength x:Key="ScrollBarRowHeight"><DynamicResource Key="{x:Static System.Windows.SystemParameters.CaptionHeightKey}" /></w:GridLength>
<w:GridLength x:Key="ScrollBarRowHeight"><x:Static x:Key="System.Windows.SystemParameters.HorizontalScrollBarHeight" /></w:GridLength>

Resulting both in the same compile-time error:

Cannot add content to object of type 'System.Windows.GridLength'.

Questions

  • Is it possible to do this declaratively in XAML?
  • If yes, how?
  • If no, is there a neat solution which does not include code-behind?

Thanks in advance!

1

There are 1 answers

0
Sheridan On BEST ANSWER

I'm wondering why don't you just use the SystemParameters.HorizontalScrollBarHeight value directly in your XAML, instead of trying to duplicate its value? (Added from comment)

On the SystemParameters.HorizontalScrollBarHeight page that you provided a link to, there is a code example which shows you exactly how to use the various SystemParameters properties in both XAML and code:

<Button FontSize="8" Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="5"      
     HorizontalAlignment="Left" 
     Height="{x:Static SystemParameters.CaptionHeight}"
     Width="{x:Static SystemParameters.IconGridWidth}">
     SystemParameters
</Button>

...

Button btncsharp = new Button();
btncsharp.Content = "SystemParameters";
btncsharp.FontSize = 8;
btncsharp.Background = SystemColors.ControlDarkDarkBrush;
btncsharp.Height = SystemParameters.CaptionHeight;
btncsharp.Width = SystemParameters.IconGridWidth;
cv2.Children.Add(btncsharp);

From the linked page:

In XAML, you can use the members of SystemParameters as either a static property usage, or a dynamic resource references (with the static property value as the key). Use a dynamic resource reference if you want the system based value to update automatically while the application runs; otherwise, use a static reference. Resource keys have the suffix Key appended to the property name.

So if you want the values to update while the application is running, then you should be able to use these properties in a Binding like this:

<Button FontSize="8" Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="5"      
     HorizontalAlignment="Left" 
     Height="{Binding Source={x:Static SystemParameters.CaptionHeight}}"
     Width="{Binding Source={x:Static SystemParameters.IconGridWidth}}">
     SystemParameters
</Button>

You should also be able to use it as a DynamicResource in this way:

Property="{DynamicResource {x:Static SystemParameters.CaptionHeight}}"