【发布时间】:2013-10-22 16:04:40
【问题描述】:
为了使用 Shift 键在 Wrap 面板中选择多个复选框。
在 Shift Keydown 上捕获鼠标按下事件位置,在第二次鼠标按下时使用 shift keydown,获取选择的 2 个位置,然后需要在选定区域中选择复选框控件。
如何在 2 个位置 (System.Window.Point) 或 System.Windows.rect 中找到控件。以下代码选择了 wrappanel(lesscolorpanel) 中的所有复选框。
private System.Windows.Point startPoint;
System.Windows.Point checkpPoint;
private System.Windows.Point PointWhereMouseIs;
private void LessColourPanel_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
if (startPoint == checkpPoint)
{
//GET THE MOUSE POSITION
startPoint = Mouse.GetPosition(lessColourPanel);
PointWhereMouseIs = checkpPoint;
}
else if(PointWhereMouseIs==checkpPoint)
{
//CAPTURE END MOUSE POSITION
PointWhereMouseIs = Mouse.GetPosition(lessColourPanel);
//FIND CONTROLS WIHIN RECTANGLE
Rect selareaRect = new Rect(startPoint, PointWhereMouseIs);
foreach (System.Windows.Controls.CheckBox chkitemBox in FindVisualChildren<System.Windows.Controls.CheckBox>(lessColourPanel))
{
var rectBounds = VisualTreeHelper.GetDescendantBounds(chkitemBox);
Vector vector = VisualTreeHelper.GetOffset(chkitemBox);
rectBounds.Offset(vector);
if (rectBounds.IntersectsWith(selareaRect))
{
chkitemBox.IsChecked = true;
}
}
startPoint = checkpPoint;
}
}
}
【问题讨论】:
-
不要在 WPF 的过程代码中创建或操作 UI 元素。这就是 XAML 的用途。删除所有这些代码并为此使用
ItemsControl和适当的 ViewModel。 -
@highcore,谢谢你,但是它如何帮助我使用 shift 键实现多选,你能给我举个例子吗?
-
我不确定你想要达到什么目的。默认情况下,
CheckBox与任何其他 CheckBox 没有任何关系。因此,您无需按 shift 或任何其他键即可获得多选。 -
使用shift键多选是指“按住shift键选择开始复选框和结束复选框,在这个动作中选择两个位置之间的复选框。
-
我已经更新了我的问题,使用 shift keydown 找到解决方案并找到鼠标的开始和结束位置,选中 2 点/矩形内的复选框。
标签: wpf c#-4.0 checkbox multi-select