我创建了一个附加行为来尝试实现您想要做的事情。
附加行为代码:
public static class ElementFocusBehavior
{
public static readonly DependencyProperty ElementToFocusProperty =
DependencyProperty.RegisterAttached("ElementToFocus", typeof (FrameworkElement), typeof (ElementFocusBehavior), new PropertyMetadata(default(FrameworkElement), PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var button = dependencyObject as Button;
if (button == null) return;
if (button.IsLoaded)
{
AddClickHandler(button);
}
else
{
button.Loaded += ButtonOnLoaded;
}
}
private static void ButtonOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var button = (Button) sender;
button.Loaded -= ButtonOnLoaded;
AddClickHandler(button);
}
static void AddClickHandler(Button button)
{
button.Click += ButtonOnClick;
}
private static void ButtonOnClick(object sender, RoutedEventArgs routedEventArgs)
{
var fe = GetElementToFocus(sender as Button) as FrameworkElement;
if (fe == null) return;
fe.Focus();
}
public static void SetElementToFocus(Button button, FrameworkElement value)
{
button.SetValue(ElementToFocusProperty, value);
}
public static FrameworkElement GetElementToFocus(Button button)
{
return (FrameworkElement) button.GetValue(ElementToFocusProperty);
}
}
以及 Button 的 XAML:
<Button Content="Reset" local:ElementFocusBehavior.ElementToFocus="{Binding ElementName=TextBoxThree, Path=.}" />
我的 MainWindow 中的示例代码:
<StackPanel>
<TextBox Name="TextBoxOne" />
<TextBox Name="TextBoxTwo" />
<TextBox Name="TextBoxThree" />
<Button Content="Reset" local:ElementFocusBehavior.ElementToFocus="{Binding ElementName=TextBoxThree, Path=.}" />
</StackPanel>
基本上,我所做的是,
- 有一个附加的行为来存储要聚焦的元素,
- 然后在附加的行为中将事件处理程序添加到按钮 Click 事件,
- 在 Click 事件中将焦点设置在
ElementToFocus
元素上
希望这可以帮助。