我在按钮点击事件中调用了以下类/行为。问题是它在button_click事件之后被调用。如何在按钮点击事件之前调用它? 下面提到的样式在App.xaml中定义为全局使用
XAML:
<Style TargetType="Button">
<Setter Property="local:DefaultButtonBehaviour.DefaultButton" Value="True" />
</Style>
CODE:
public static class DefaultButtonBehaviour
{
/// 1. This is the boolean attached property with its getter and setter:
public static readonly DependencyProperty DefaultButtonProperty =
DependencyProperty.RegisterAttached
(
"DefaultButton",
typeof(bool),
typeof(DefaultButtonBehaviour),
new UIPropertyMetadata(false, OnDefaultButtonPropertyChanged)
);
public static bool GetDefaultButton(DependencyObject obj)
{
return (bool)obj.GetValue(DefaultButtonProperty);
}
private static void SetDefaultButton(DependencyObject obj, bool value)
{
obj.SetValue(DefaultButtonProperty, value);
}
/// 2. This is the change event of our attached property value:
/// * We get in the first parameter the dependency object to which the attached behavior was attached
/// * We get in the second parameter the value of the attached behavior.
/// * The implementation of the behavior is to check if we are attached to a textBox, and if so and the value of the behavior
/// is true, hook to the PreviewGotKeyboardFocus of the textbox.
private static void OnDefaultButtonPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
{
ButtonBase button = dpo as ButtonBase;
if (button != null)
{
if ((bool)args.NewValue)
{
button.Click += OnDefaultButtonClick;
}
else
{
button.Click -= OnDefaultButtonClick; ;
}
}
}
private static void OnDefaultButtonClick(object sender, RoutedEventArgs e)
{
ButtonBase btn = (ButtonBase)sender;
DependencyObject focusScope = FocusManager.GetFocusScope(btn);
FocusManager.SetFocusedElement(focusScope, btn);
Keyboard.Focus(btn);
}
}
答案 0 :(得分:0)
如果我正确地遵循了这个问题,你可以通过连接Preview
事件来解决这个问题。挂钩PreviewMouseDown和PreviewKeyDown(这样您就可以处理用户使用返回键激活按钮的情况)。