1.界面模板代码部分
- <Window.Resources>
- <Style x:Key="IconButton" TargetType="Button">
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="Button">
- <Border x:Name="border"
- BorderBrush="{TemplateBinding BorderBrush}"
- BorderThickness="{TemplateBinding BorderThickness}"
- Background="{TemplateBinding Background}"
- Padding="{TemplateBinding Padding}"
- SnapsToDevicePixels="True"
- CornerRadius="8,8,8,8">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto"/>
- <ColumnDefinition Width="*"/>
- </Grid.ColumnDefinitions>
- <Image Grid.Column="0" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(localModel:ButtonExtensions.IconPath)}" Width="16" Height="16" Margin="4,0"/>
- <ContentPresenter Grid.Column="1" x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}"
- Content="{TemplateBinding Content}"
- ContentStringFormat="{TemplateBinding ContentStringFormat}"
- HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
- VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
- SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
- RecognizesAccessKey="True"
- Margin="{TemplateBinding Padding}"/>
- </Grid>
- </Border>
- <ControlTemplate.Triggers>
- <Trigger Property="IsMouseOver" Value="True">
- <Setter TargetName="border" Property="Background" Value="#7DB8FF"/>
- </Trigger>
- <Trigger Property="IsPressed" Value="True">
- <Setter TargetName="border" Property="Background" Value="#6CADFF "/>
- </Trigger>
- <Trigger Property="IsEnabled" Value="False">
- <Setter Property="Opacity" TargetName="border" Value="0.6"/>
- </Trigger>
- </ControlTemplate.Triggers>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </Window.Resources>
2.在工程中添加类,用于编辑附加属性,主要是为了设置图标地址。下面为附加属性代码
- //通过附加属性来设置图标的路径
- public static class ButtonExtensions
- {
- public static readonly DependencyProperty IconPathProperty = DependencyProperty.RegisterAttached(
- "IconPath", typeof(string), typeof(ButtonExtensions), new PropertyMetadata(null));
-
- public static string GetIconPath(DependencyObject obj)
- {
- return (string)obj.GetValue(IconPathProperty);
- }
-
- public static void SetIconPath(DependencyObject obj, string value)
- {
- obj.SetValue(IconPathProperty, value);
- }
- }
3.界面按钮代码实现代码,如下
- <Button Grid.Row="1" Grid.Column="0" x:Name="BtnLoadImage"
- Style="{StaticResource IconButton}"
- localModel:ButtonExtensions.IconPath="pack://application:,,,/Resources/OpenPath.png"
- Width="100" Height="40"
- Content="Load Image"
- Background="#6CADFF" BorderBrush="Transparent"/>