我实现了一个带有图像的简单按钮:
如您所见,我公开了一个ButtonCommand属性,以便能够将ICommand附加到此UserControl:
public partial class ImageButton : UserControl { ////// The dependency property that gets or sets the source of the image to render. /// public static DependencyProperty ImageSourceProperty = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ImageButton)); public static DependencyProperty TextProperty = DependencyProperty.Register("ButtonText", typeof(string), typeof(ImageButton)); public static DependencyProperty ButtonCommandProperty = DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(ImageButton)); public ImageButton() { this.DataContext = this; InitializeComponent(); } ////// Gets or sets the button command. /// public ICommand ButtonCommand { get { return (ICommand)GetValue(ImageButton.ButtonCommandProperty); } set { SetValue(ImageButton.ButtonCommandProperty, value); } } ////// Gets or sets the button image. /// public ImageSource ButtonImage { get { return (ImageSource)GetValue(ImageButton.ImageSourceProperty); } set { SetValue(ImageButton.ImageSourceProperty, value); } } ////// Gets or sets the button text. /// public string ButtonText { get { return (string)GetValue(ImageButton.TextProperty); } set { SetValue(ImageButton.TextProperty, value); } } }
然后,当我声明我的按钮时,它给出了:
还有badaboom,当我点击我的ImageButton时,什么都不会发生.当我用一个简单的按钮替换ImageButton时,会调用ICommand.
我甚至试图简单地扩展Button类并绑定一个ICommand,但再次,它没有工作......
帮助赞赏!
谢谢.
您可以使用样式和几个附加属性以更清洁的方式实现此目的.
附加的属性将存储您的特定信息.该样式将使用这些属性并构建您想要的外观.
该元素仍然是一个按钮,所以命令和其他一切都可以工作.
public class ImageButton { public static ImageSource GetImage(DependencyObject obj) { return (ImageSource)obj.GetValue(ImageProperty); } public static void SetImage(DependencyObject obj, ImageSource value) { obj.SetValue(ImageProperty, value); } public static readonly DependencyProperty ImageProperty = DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null)); public static String GetCaption(DependencyObject obj) { return (String)obj.GetValue(CaptionProperty); } public static void SetCaption(DependencyObject obj, String value) { obj.SetValue(CaptionProperty, value); } public static readonly DependencyProperty CaptionProperty = DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(ImageButton), new UIPropertyMetadata(null)); }
然后,您可以使用它来声明按钮:
注意:
我很确定通过"模板"属性并使用ControlTemplate和TemplateBindings会更清晰,但这意味着要重新创建内容周围的边框和其他内容,所以如果您只想定义默认值我认为,"内容",我的例子将是要走的路.