WPF C# Button 加载图片,背景图片

vs2010 

界面:




    
        

        
    
    
    
        
            
            
        
        

        
    

逻辑代码:

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Input;
using System.Windows.Controls;


namespace ButtonLoadIMG
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 右击图片->属性->1 复制到输出目录:始终复制, 2 生成操作:内容
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LoadIMG("IMG/person.png");


            MouseButtonEventHandler mouseBtnEventHandler = new MouseButtonEventHandler(this.buttonCS_MouseLeftButtonDown);
            btnCS.AddHandler(System.Windows.Controls.Button.MouseDownEvent, mouseBtnEventHandler, true);
            //btnCS.AddHandler(System.Windows.Controls.Button.MouseDownEvent, new MouseButtonEventHandler(this.btnCS_MouseLeftButtonUp), true);            
        }


        private void LoadIMG(string strIMG)
        {
            #region 加载logo图片
            BitmapImage bitmapImg = new BitmapImage();
            bitmapImg.BeginInit();
            bitmapImg.UriSource = new System.Uri(strIMG, UriKind.RelativeOrAbsolute); ;
            //bitmapImg.DecodePixelWidth = 200;
            bitmapImg.EndInit();
            imgBtnCS.Stretch = Stretch.Uniform;
            imgBtnCS.ImageSource = bitmapImg;
            #endregion
        }


        private void SetBtnBackgroundIMG(string strIMGPath)
        {
            #region 设置图片
            Image img = new Image();
            BitmapImage bitmapImg = new BitmapImage();
            bitmapImg.BeginInit();
            bitmapImg.UriSource = new System.Uri(strIMGPath, UriKind.RelativeOrAbsolute); ;
            //bitmapImg.DecodePixelWidth = 200;
            bitmapImg.EndInit();
            //imgBtnCS.Stretch = Stretch.Uniform;
            img.Source = bitmapImg;
            btnCS.Content = img;
            #endregion
        }


        private void buttonCS_MouseEnter(object sender, MouseEventArgs e)
        {
            SetBtnBackgroundIMG("IMG/group.png");
        }


        private void buttonCS_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            SetBtnBackgroundIMG("IMG/ChangeGrp.png");
        }


        private void btnCS_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SetBtnBackgroundIMG("IMG/group.png");
        }


        private void buttonCS_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            SetBtnBackgroundIMG("IMG/person.png");
        }


        //private void btnCS_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        //{
        //    //SetBtnBackgroundIMG("IMG/group.png");
        //}
        
    }
}



你可能感兴趣的:(C#,WPF)