WPF自定义Button控件

WPF自定义Button控件,第1张

这个要靠依赖属性来做啦!~

第一步,写个自己的button继承类,增加字段属性

public class MyButton:Button

{

public ImageSource ImgSource

{

get { return (ImageSource)GetValue(SourceProperty)}

set { SetValue(SourceProperty, value)}

}

public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("ImgSource", typeof(ImageSource), typeof(MyButton), null)

}

第二步,用blend编辑button类的模板,把TargetType="Button"改成TargetType="local:MyButton"喔!~找到ContentPresenter所在行,用以下代码代替:

<StackPanel Orientation="Horizontal">

<Image Source="{TemplateBinding ImgSource}"/>

<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>

</StackPanel>

最后就可以直接在控件中设定啦!~

<local:MyButton Content="Button" Height="45" Width="120" Style="{StaticResource ButtonStyle1}" Padding="10,0,0,0" ImgSource="bandeng.jpg"/>

你的控件 Z 不会原本就已经有内容了吧

Window 这种 ContentControl,只能有一个控件包含在里面,要包含多个,你得先把布局控件放 Window 的 Content 里,再在布局空间里放多个按钮


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11634065.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存