原因:
由于某些控件内部有一些内建的事件处理,其MouseDown事件(包括MouseUp等)在处理完成之后将Handled标志置为true,附加事件PreviewMouseDown事件也就不再被执行,所以普通的MouseDown事件代码是不会有作用的。如果要使用MouseDown事件,要么使用PreviewMouseDown事件来替代,要么使用AddHandler来添加自定义的路由事件处理。
解决方案:
1.使用相应的Preview事件。须注意隧道类型的事件是从根元素开始执行的。
2.使用AddHandler添加自定义的路由事件。
button1.PreviewMouseDown += (object sender, MouseButtonEventArgs e) =>
{
//这里写事件触发时的操作
};
或
button1.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler((s, e) =>
{
//这里写事件触发时的操作
}), true);
或
button1.AddHandler(Button.MouseDownEvent, new RoutedEventHandler((object sender, RoutedEventArgs e) =>
{
//这里写事件触发时的操作
}), true);
参考: