在开发过程中,我们可以直接在按钮上进行按钮模板的定义,例如下面的代码。
<Button Width="40" Height="40" Style="{DynamicResource CubeImageButtonStyle}" Click="Button_Click" Content="点赞">
<Button.Background>
<ImageBrush ImageSource="/assests/favicon.png" Stretch="Fill"/>
</Button.Background>
</Button>
<Setter Property="Template"
<Setter.Value>
<ControlTemplate>
<Border BorderThickness="0" CornerRadius="3">
<Border.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#4696F2" Offset="0.5"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter Content="{TemplateBinding ContentControl.Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Grid.Column="0" Grid.Row="1" Style="{StaticResource FlatButtonStyle}" HorizontalAlignment="Center" VerticalAlignment="Top" Width="48" Height="16" FontSize="10" Background="#4696F2" Content="获取"></Button>
</Grid>
这样的代码在界面比较简单时,还无所谓,但是随着控件的样式越来越复杂,可能会成为一团乱麻,这对于追求优雅代码的我们来说,可能是难以忍受的,所以往往会使用资源引用来完成。
StaticResource
例如,我们可以在当前页面代码中定义对应的样式,这种样式可以使用 StaticResource 的形式引入。但是这样的引用形式,没有对象图的访问权限,意味着无法访问资源依赖的其他资源。
<Window.Resources>
<Style TargetType="Button" x:Key="FlatButtonStyle">
<Setter Property="Margin" Value="4" />
<Setter Property="FontWeight" Value="Black"/>
<Setter Property="Foreground" Value="Black" />
<Setter Property="BorderThickness" Value="0"/>
</Window.Resources>
DynamicResource
将上述代码中的{StaticResource FlatButtonStyle} 改成{StaticResource FlatButtonStyle}则会在运行时加载样式,并可以访问相应的对象图。
当然,这样的更改意义不大,如果该FlatButtonStyle引用了其他样式或元素,会发生作用。
<Grid
<Button Grid.Column="0" Grid.Row="1" Style="{StaticResource FlatButtonStyle}" HorizontalAlignment="Center" VerticalAlignment="Top" Width="48" Height="16" FontSize="10" Background="#4696F2" Content="获取"></Button>
</Grid>
注意事项
1、由于XAML语法脱胎于XML语法,而XML语法中本身对某些输入字符,如“<>”存在限制,所以在XAML中也会出现这类问题,并会被Visual Studio检测出错误而无法编译,需要使用UTF-8编码进行转换。