Detect whether the mouse button is pressed or released using the MouseButtonState property.

image_pdfimage_print


   
  


<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DetectMouseButtonState" Height="400" Width="400">

  <StackPanel Height="100" Width="100" 
      MouseLeftButtonDown="HandleButtonDown" 
      MouseLeftButtonUp="HandleButtonDown" 
      Background="Red"
      DockPanel.Dock="Left">
    <TextBlock>Click on Me</TextBlock>
  </StackPanel>
</Window>
//File:Window.xaml.cs

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

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        void HandleButtonDown(object sender, MouseButtonEventArgs e)
        {
            StackPanel sourceStackPanel = e.Source as StackPanel;

            if (e.ButtonState == MouseButtonState.Pressed)
            {
                sourceStackPanel.Width = 200;
                sourceStackPanel.Height = 200;
            }else if (e.ButtonState == MouseButtonState.Released)
            {
                sourceStackPanel.Width = 100;
                sourceStackPanel.Height = 100;
            }
        }
    }
}