本文介绍WPF一种自定义按钮的方法。
实现效果如下图所示:
// ButtonStyles.xaml <Style x:Key="CustomButton" TargetType="{x:Type local:CustomButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:CustomButton}"> <Grid x:Name="container"> <Image Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Source="{Binding ButtonImage,RelativeSource={RelativeSource Mode=TemplatedParent}}"> <Image.RenderTransformOrigin> <Point X="0.5" Y="0.5"/> </Image.RenderTransformOrigin> <Image.RenderTransform> <ScaleTransform x:Name="scaletrans" ScaleX="1" ScaleY="1"/> </Image.RenderTransform> </Image> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Opacity" Value="0.5" TargetName="container"/> </Trigger> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="#2c000000" TargetName="container"/> </Trigger> <Trigger Property="IsPressed" Value="True"> <Trigger.EnterActions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="scaletrans" Storyboard.TargetProperty="(ScaleTransform.ScaleX)" To="0.8" Duration="0:0:0.15" AutoReverse="True"/> <DoubleAnimation Storyboard.TargetName="scaletrans" Storyboard.TargetProperty="(ScaleTransform.ScaleY)" To="0.8" Duration="0:0:0.15" AutoReverse="True"/> </Storyboard> </BeginStoryboard> </Trigger.EnterActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> // CustomButton.cs public class CustomButton : Button { public ImageSource ButtonImage { get { return (ImageSource)GetValue(ButtonImageProperty); } set { SetValue(ButtonImageProperty, value); } } public static readonly DependencyProperty ButtonImageProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(CustomButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); } // App.xaml 合并资源 <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source=".../ButtonStyles.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> // view.xaml 使用 <Grid> <customcontrols:CustomButton Width="48" Height="48" Style="{StaticResource CustomButton}" ButtonImage="/Louzi.Paint;component/Images/Toolbar/write.png"/> </Grid>
以上就是C# WPF 自定义按钮的方法的详细内容,更多关于C# WPF 自定义按钮的资料请关注呐喊教程其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。