WPF:单击并拖动以选择多个复选框

时间:2015-02-09 02:42:29

标签: wpf checkbox visual-studio-2013 multi-select

我想达到的效果:

  1. 按住鼠标左键。
  2. 鼠标移动。
  3. 切换鼠标经过的任何复选框。
  4. 简单,对吧? ; - ;

    感谢。

1 个答案:

答案 0 :(得分: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>

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