WPF Button MouseEnter and MouseLeave together play as MouseOver

FredGrit發表於2024-08-25
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp286
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Button btn { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            ButtonMouseEnterMouseLeave();
        }

        private void ButtonMouseEnterMouseLeave()
        {
            btn = new Button();
            btn.Content = "Button!";
            btn.FontSize = 30;
            btn.Width = 300;
            btn.Height = 100;
            btn.Background = new SolidColorBrush(Colors.Red);
            btn.MouseEnter += Btn_MouseEnter;
            btn.MouseLeave += Btn_MouseLeave;
            this.Content = btn;
        }

        private void Btn_MouseLeave(object sender, MouseEventArgs e)
        {
            btn.Background = new SolidColorBrush(Colors.Red);
        }

        private void Btn_MouseEnter(object sender, MouseEventArgs e)
        {
            btn.Background = new SolidColorBrush(Colors.Blue);
        }
    }
}

相關文章