效果如下:
这次我们将利用RadioButton自定义模板实现图文按钮的效果,其中图标采用阿里巴巴图标库,从网上下载阿里巴巴图标库的ttf文件,并导入到项目中备用。
然后我们编写前端代码
<UniformGrid Columns="4" Height="40" Width="400">
<RadioButton Style="{StaticResource defaultRadioStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="" FontSize="18" FontFamily="Assets/Fonts/#iconfont" VerticalAlignment="Center"/>
<TextBlock Text="首页" Margin="10 0 0 0" VerticalAlignment="Center"/>
</StackPanel>
</RadioButton>
<RadioButton Style="{StaticResource defaultRadioStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="" FontSize="18" FontFamily="Assets/Fonts/#iconfont" VerticalAlignment="Center"/>
<TextBlock Text="邮件" Margin="10 0 0 0" VerticalAlignment="Center"/>
</StackPanel>
</RadioButton>
<RadioButton Style="{StaticResource defaultRadioStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="" FontSize="18" FontFamily="Assets/Fonts/#iconfont" VerticalAlignment="Center"/>
<TextBlock Text="图片" Margin="10 0 0 0" VerticalAlignment="Center"/>
</StackPanel>
</RadioButton>
<RadioButton Style="{StaticResource defaultRadioStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="" FontSize="18" FontFamily="Assets/Fonts/#iconfont" VerticalAlignment="Center"/>
<TextBlock Text="短信" Margin="10 0 0 0" VerticalAlignment="Center"/>
</StackPanel>
</RadioButton>
</UniformGrid>
这里我们写了4个RadioButton,并编写一个静态样式:defaultRadioStyle
<Style x:Key="defaultRadioStyle" TargetType="RadioButton">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Foreground" Value="#88949A"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid Background="{TemplateBinding Background}">
<Border x:Name="border" BorderBrush="{TemplateBinding Foreground}" BorderThickness="0 0 0 0 "/>
<ContentPresenter Focusable="False"
RecognizesAccessKey="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Foreground" Value="#8CEDCB"/>
<Setter Property="BorderThickness" Value="0 0 0 1" TargetName="border"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
需要注意的是,图标被看成是一个字符串,所以用TextBlock 的text属性,注意图标是以转义字符串的形式存在的。这样一个简单又漂亮的导航栏就做好了!