如何使用多个StaticResources在XAML中分配属性值

时间:2017-08-23 13:56:05

标签: c# wpf xaml staticresource

MainWindow.xaml中,我尝试使用两个StaticResource元素来定义网格中TextBox边框的粗细。我似乎无法在StaticResource规范中多次使用BorderThickness

代码片段有效,

xmlns:syw="clr-namespace:System.Windows;assembly=PresentationFramework"
<Window.Resources>
    <syw:Thickness x:Key="thick">5.0</syw:Thickness>
    <syw:Thickness x:Key="thin">1.0</syw:Thickness>
</Window.Resources>

定义行数和列数后,仍然在<Grid>部分中

<TextBox Name="c00" Grid.Row="1" Grid.Column="1" BorderBrush="Black" BorderThickness="{StaticResource ResourceKey=thick}"/>
<TextBox Name="c01" Grid.Row="2" Grid.Column="2" BorderBrush="Black" BorderThickness="5.0, 5.0, 1.0, 1.0"/>

此代码符合并显示两个TextBox,第一个在TextBox的所有四个边上具有相同的边框粗细,第二个具有一个厚度用于左侧和顶侧,第二个厚度用于右侧和底侧文本框。

我希望能够做的是多次使用StaticResource代替上面第二行中的数字,因为我有很多TextBox,并希望能够通过改变几个来改变边框厚度数字,即thickthin。但是,当我尝试时,

<TextBox Name="c00" Grid.Row="1" Grid.Column="1" BorderBrush="Black"
         BorderThickness="{StaticResource ResourceKey=thick},{StaticResource ResourceKey=thick},{StaticResource ResourceKey=thin},{StaticResource ResourceKey=thin}"/>

编辑器指出逗号在该位置是意外的,不会编译。

我只是错误地格式化了吗?

2 个答案:

答案 0 :(得分:4)

宣布其他资源

<sys:Double x:Key="dThick">5.0</sys:Double>
<sys:Double x:Key="dThin">1.0</sys:Double>

并使用标签语法和边框每边的双倍资源值设置厚度:

<TextBox.BorderThickness>
    <syw:Thickness Left="{StaticResource dThick}" Top="{StaticResource dThick}"
                   Right="{StaticResource dThin}" Bottom="{StaticResource dThin}"/>

</TextBox.BorderThickness>

BorderThickness="{StaticResource ResourceKey=thick}"是一个标记扩展,工作正常。

BorderThickness="5.0, 5.0, 1.0, 1.0"有效,因为有关联的类型转换器可将带有逗号分隔数字的string转换为Thickness

BorderThickness="{StaticResource ResourceKey=thick},{StaticResource ResourceKey=thick},{StaticResource ResourceKey=thin},{StaticResource ResourceKey=thin}" - 在xaml中不受支持

答案 1 :(得分:0)

我认为你想要做的是用所需的参数定义厚度,如下所示:

<Window.Resources>
    <syw:Thickness x:Key="borderThickness">5.0, 5.0, 1.0, 1.0</syw:Thickness>
</Window.Resources>

您可以按如下方式使用:

<TextBox BorderThickness="{StaticResource borderThickness}"/>

这应该会为您提供您正在寻找的行为。