我在WPF中使用工具栏。现在,当我点击仅限工具栏时,我想检测工具栏上的点击。我怎样才能做到这一点 ?任何建议?
答案 0 :(得分:1)
您只需要为工具栏定义预览鼠标按下处理程序...
<ToolBar Name="toolBar1" ToolBarTray.IsLocked="False" PreviewMouseDown="toolBar1_PreviewMouseDown" >
<Menu ToolBar.OverflowMode="AsNeeded">
<MenuItem Header="File" />
<MenuItem Header="New" />
</Menu>
</ToolBar>
然后在处理程序中,执行命中测试以确定您是否在Thumb上,这是实现抓握的控件...
private void toolBar1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
Point p = e.GetPosition(toolBar1);
IInputElement ie = toolBar1.InputHitTest(p);
Thumb t = GetParent<Thumb>(ie as DependencyObject);
if(t != null)
{
// we have clicked on the grip...
}
}
}
private T GetParent<T>(DependencyObject d) where T : class
{
while (d != null && !(d is T))
{
d = VisualTreeHelper.GetParent(d);
}
return d as T;
}