【发布时间】:2017-05-15 09:03:57
【问题描述】:
我有以下在按钮单击事件中被调用的类/行为。问题是它在 button_click 事件之后被调用。如何在按钮单击事件之前调用它? 下面提到的样式在 App.xaml 中定义以供全局使用
XAML:
<Style TargetType="Button">
<Setter Property="local:DefaultButtonBehaviour.DefaultButton" Value="True" />
</Style>
代码:
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);
}
}
【问题讨论】:
-
如何区分点击的“之前”和“之后”?单击是事件,一旦事件发生,所有处理程序都会被调用,您需要水晶球在事件发生之前调用它们。我可能没有得到你的问题
-
感谢收看。我在其中一个屏幕中有一个按钮单击事件。首先触发按钮单击,然后调用此行为。我想要反过来。
-
对不起,我还没有关注,假设您没有附加任何点击行为,那么在您的情况下点击会发生什么?
-
@sskher 你能告诉我们,这种行为会做什么吗?