WPF:单击并拖动到 Select 个复选框

WPF: Click And Drag To Select Multiple CheckBoxes

我要达到的效果:

  1. 按住鼠标左键。
  2. 鼠标移动。
  3. 切换鼠标经过的任何复选框。

很简单吧? ;-;

谢谢。

不太难。

代码隐藏

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Checkbox_OnMouseEnter(object sender, MouseEventArgs e)
    {
        var checkbox = sender as CheckBox;

        if (e.LeftButton == MouseButtonState.Pressed)
        {
            if (checkbox != null)
            {
                checkbox.IsChecked = !checkbox.IsChecked;
            }
        }
    }

    private void UIElement_OnGotMouseCapture(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var checkbox = sender as CheckBox;
            if (checkbox != null)
            {
                checkbox.IsChecked = !checkbox.IsChecked;
                checkbox.ReleaseMouseCapture();
            }
        }
    }

XAML

<Window x:Class="ClickAndDrag.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
    <CheckBox MouseEnter="Checkbox_OnMouseEnter" GotMouseCapture="UIElement_OnGotMouseCapture"/>
</StackPanel>

释放鼠标捕获的原因是为了防止复选框在单击时吞噬所有事件。