【问题标题】:Assign static value to GridLength resource为 GridLength 资源分配静态值
【发布时间】:2014-01-29 23:31:08
【问题描述】:

案例

我在我的 WPF 窗口中定义了一系列 GridLenghts 作为资源:

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

由于这个滚动条高度是可变的,取决于所使用的操作系统,我想重构这行代码以使用静态参数值SystemParameters.HorizontalScrollBarHeight

问题

这两行我都试过了:

<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>

导致相同的编译时错误:

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

问题

  • 是否可以在 XAML 中以声明方式执行此操作?
  • 如果是,怎么做?
  • 如果没有,是否有不包含代码隐藏的简洁解决方案?

提前致谢!

【问题讨论】:

  • 为什么不直接使用SystemParameters.HorizontalScrollBarHeight 值而不是尝试复制它?
  • @Sheridan,如何直接使用?
  • 你想用什么控件属性?
  • 我会将它用于控件属性 RowDefinition.Height。问题是,我经常引用资源并且喜欢在 XAML 文件之上定义它。
  • 那到底有什么帮助?

标签: c# .net wpf xaml gridlength


【解决方案1】:

我想知道为什么不直接在 XAML 中使用 SystemParameters.HorizontalScrollBarHeight 值,而不是尝试复制它的值? (从评论中添加)

提供链接的 SystemParameters.HorizontalScrollBarHeight 页面上,有一个代码示例向您展示了如何在 XAML 中使用各种 SystemParameters 属性em> 代码:

<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);

来自链接页面:

在 XAML 中,您可以将 SystemParameters 的成员用作静态属性用法或动态资源引用(以静态属性值作为键)。如果您希望基于系统的值在应用程序运行时自动更新,请使用动态资源引用;否则,请使用静态引用。资源键具有附加到属性名称的后缀 Key。

因此,如果您希望在应用程序运行时更新值,那么您应该能够像这样在Binding 中使用这些属性:

<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>

应该也可以通过这种方式将其用作DynamicResource

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多