天天看點

在VS2005中設定WPF中自定義按鈕的事件

原文:

在VS2005中設定WPF中自定義按鈕的事件

上篇講了如何在Blend中繪制圓角矩形(

http://blog.csdn.net/johnsuna/archive/2007/08/13/1740781.aspx

),本篇繼續下一步驟,如何自定義按鈕的事件。

(1)首先,在VS2005中打開上篇所建的項目(File - Open Project),找到LinearGradientButton.csproj(這是我這裡的項目名稱),打開之後,輕按兩下LinearGradientDemo.xaml.cs,在LinearGradientDemo的構造函數的上面,鍵入:

Color initColor;//這句用來儲存最初的按鈕底色值

(2)在你所看到LinearGradientDemo的構造函數中有句this.InitializeComponent();,再在下面鍵入如下用灰色底突出顔色的代碼,得到:

        public LinearGradientDemo()

  {

   this.InitializeComponent();

            this.RoundRect_LinearGradientBottom.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(ClickRect_MouseLeftButtonDown);

            this.RoundRect_LinearGradientBottom.MouseEnter += new System.Windows.Input.MouseEventHandler(EnterButton);

            this.RoundRect_LinearGradientBottom.MouseLeave += new System.Windows.Input.MouseEventHandler(LeaveButton);

            initColor = ((SolidColorBrush)(this.RoundRect_Bg.Fill)).Color;

  }

說明:

(a)這裡的ClickRect_MouseLeftButtonDown是當滑鼠左鍵在按鈕上(确切地說是在RoundRect_LinearGradientBottom這個圓角矩形上)按下之後所發生的事件。

(b)EnterButton則是當滑鼠進入RoundRect_LinearGradientBottom後所發生的事件(MouseEnter)。

(c)LeaveButton是當滑鼠離開RoundRect_LinearGradientBottom後所發生的事件(MouseLeave)。

(3)鍵入下面代碼:

        void ClickRect_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)

        {

            MessageBox.Show("你點選我了!");

        }

        void EnterButton(object sender, System.Windows.Input.MouseEventArgs e)

            this.RoundRect_Bg.Fill = new SolidColorBrush(Color.FromArgb(255, 200, 100, 0));

        void LeaveButton(object sender, System.Windows.Input.MouseEventArgs e)

            this.RoundRect_Bg.Fill = new SolidColorBrush(initColor);

(4)按F5或Ctrl+F5運作它,得到如下所示界面:

在VS2005中設定WPF中自定義按鈕的事件

當滑鼠移進按鈕時,顔色變了,離開後按鈕顔色恢複為最初的顔色。

當滑鼠點選按鈕時,彈出“你點選我了!”的對話框。

這裡用到了System.Windows.Shapes.Rectangle從UIElement繼承的各種公共事件(詳見SDK:ms-help://MS.LHSMSSDK.1033/MS.LHSNETFX30SDK.1033/fxref_presentationcore/html/229bc431-4295-fd39-706f-09abde5e7be5.htm)來實作自定義控件的事件處理。

繼續閱讀