XAML 中的 WPF GridLength

问题描述 投票:0回答:2

我试图在 Common.xaml 中定义一个公共宽度资源,它将由不同的控件共享,如下所示:

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

然后我在 ButtonStyle.xaml 中定义的 Button 样式中使用它

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

Common.xaml 包含在 App.xaml 中 ResourceDictionary 定义中的 ButtonStyle.xaml 之前。当我运行该应用程序(在 .Net3.5 SP1 上)时,出现以下异常:

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

有人知道我做错了什么吗?预先感谢。

wpf xaml resourcedictionary gridlength
2个回答
2
投票

请注意,

Button.Width
不是
GridLength
类型。在
Grid.GridLength
中,您可以将值指定为固定、自动或星号。它仅用于
Grid
中的行、列的大小。

Button.Width
属于
double
类型。也就是说,如果您想使用资源来设置它,您需要像

这样的资源
<sys:Double x:Key="Height">200</sys:Double>

0
投票

对于任何宽度为 double 类型的控件,您可以通过 StaticResource 分配值,如下所示:

要包含在 xaml 文件中的命名空间:

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

将高度和宽度定义为资源:

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

为控件赋值:

<TextBox x:Name="TextBox" Width="{StaticResource ControlWidth}" Height="{StaticResource ControlHeight}"/>
© www.soinside.com 2019 - 2024. All rights reserved.