Custom button template in WPF

前端 未结 5 1083
深忆病人
深忆病人 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 02:56

    I have finally created a Button with image + text inside it:

    Below is the Full Code:

    Step 1 : Create a new User Control called:ImageButtonUC

    
        
            
        
    
    

    Step 2: Edit ImageButtonUC.xaml.cs

    public partial class ImageButtonUC : UserControl
        {
            public event RoutedEventHandler Click;
    
            public ImageButtonUC()
            {
                InitializeComponent();
    
            }
    
            public string Text
            {
                get { return (string)GetValue(TextProperty); }
                set { SetValue(TextProperty, value); }
            }
    
    
            public static readonly DependencyProperty TextProperty =
              DependencyProperty.Register("Text", typeof(string), typeof(ImageButtonUC), new UIPropertyMetadata(""));
    
            public ImageSource Image
            {
                get { return (ImageSource)GetValue(ImageProperty); }
                set { SetValue(ImageProperty, value); }
            }
    
            public static readonly DependencyProperty ImageProperty =
               DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButtonUC), new UIPropertyMetadata(null));
    
    
            private void button_Click(object sender, RoutedEventArgs e)
            {
    
                if (null != Click)
    
                    Click(sender, e);
    
            }
    
        }
    

    Step 3: In your xaml you can use it this way: Add the namespace as

    xmlns:Local="clr-namespace:WpfApp"
    

    And use it as:

    
    

    Note: My Image is loacted in the Resources folder here

    Reference:

    http://blogs.msdn.com/knom/archive/2007/10/31/wpf-control-development-3-ways-to-build-an-imagebutton.aspx

提交回复
热议问题