我的问题很简单。是否有可能在WPF中的keyup和keydown事件中触发mouseup和mousedown。
我在自定义控件中设置了鼠标按下和鼠标按下的事件处理程序。如果用户尝试按我的自定义按钮上的空格键,我想触发相同的内容。
private void CustomButton_MouseDown(object sender, MouseButtonEventArgs e)
{
eventlabel.Content = "Mousedown event Triggered";
}
private void CustomButton_MouseUp(object sender, MouseButtonEventArgs e)
{
eventlabel.Content = "MouseUp event Triggered";
}
private void CustomButton_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
//Need to trigger all the handlers of mousedown
}
}
private void CustomButton_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
//Need to trigger all the handlers of mouseup
}
}
答案 0 :(得分:1)
您可以使用RaiseEvent(EventArgs)在所有UIElements中引发事件。 MouseButtonArgsEventsArgs可以在KeyDown-EventHandler中使用:
MouseDevice mouseDevice = Mouse.PrimaryDevice;
MouseButtonEventArgs mouseButtonEventArgs = new MouseButtonEventArgs(mouseDevice, 0, MouseButton.Left);
mouseButtonEventArgs.RoutedEvent = Mouse.MouseDownEvent;
mouseButtonEventArgs.Source = this;
RaiseEvent(mouseButtonEventArgs);
答案 1 :(得分:0)
Tobias提到的答案对我有用。但是,它需要一些调整。
elementName.RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
{
RoutedEvent = Mouse.MouseDownEvent,
Source = this,
});
Here是参考