WPF C#Buttonロード画像、背景画像

6165 ワード

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");
        //}
        
    }
}