Custom button template in WPF

前端 未结 5 1085
深忆病人
深忆病人 2020-11-29 02:51

I want to create a simple button template with an image and text inside it. But I want to keep the System button\'s look and feel.

How do I create it, step by step?<

5条回答
  •  遥遥无期
    2020-11-29 03:03

    You can do this easily with a style and attached property:

    
        ...
        
        ...
    
    

    and

    public class ButtonProperties
    {
        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(ButtonProperties), new UIPropertyMetadata((ImageSource)null));
    }
    

    Then in markup:

    
    

    This example looks pretty hideous, but you can easily change the StackPanel to a Grid or something similar to constrain the image proportion. Using the ContentPresenter allows you to preserve the behaviour of a button allowing you to put any UIElement inside, and retaining Command support etc.

提交回复
热议问题