标签:
自定义一个按钮控件
按钮控件很简单,我们在项目中有时把样式封装起来,添加依赖属性,也是为了统一。
这里举例,单纯的图标控件怎么设置
1、UserControl界面样式
<UserControl x:Class="WpfApplication12.IconButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Loaded="IconButton_OnLoaded"> <UserControl.Resources> <Style TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Rectangle x:Name="T_Rectangle" Height="15" Width="15"> <Rectangle.Fill> <ImageBrush ImageSource="{Binding ImagesSource}"></ImageBrush> </Rectangle.Fill> </Rectangle> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}"></ContentPresenter> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="T_Rectangle" Property="Height" Value="18"></Setter> <Setter TargetName="T_Rectangle" Property="Width" Value="18"></Setter> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="T_Rectangle" Property="Height" Value="20"></Setter> <Setter TargetName="T_Rectangle" Property="Width" Value="20"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid> <Button Click="ButtonBase_OnClick"></Button> </Grid> </UserControl>
2、后台设置,我这边只添加了个图片路径和事件委托。其它的自己加吧
public partial class IconButton : UserControl { public IconButton() { InitializeComponent(); } public ImageSource ImagesSource { get { return (ImageSource)GetValue(ImagesSourceProperty); } set { SetValue(ImagesSourceProperty, value); } } public static readonly DependencyProperty ImagesSourceProperty = DependencyProperty.Register("ImagesSource", typeof(ImageSource), typeof(IconButton)); private void IconButton_OnLoaded(object sender, RoutedEventArgs e) { var data = new IconButtonModel() { ImagesSource = ImagesSource }; this.DataContext = data; } public delegate void ClickEventArgs(object sender, RoutedEventArgs e); public event ClickEventArgs Click; private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (Click != null) { Click(sender, e); } } } public class IconButtonModel { public ImageSource ImagesSource { get; set; } }
标签:
原文地址:http://www.cnblogs.com/ExMan/p/5845692.html