我想将焦点行为绑定到重置按钮,该重置按钮将焦点放在ElementToFocus属性中指定的控件
<Style TargetType="Button" x:Key="Button_Reset" BasedOn="{StaticResource Button_Default}" >
<Setter Property="ElementToFocus" />
<Setter Property="behaviors:EventFocusAttachment.ElementToFocus" Value="{Binding ElementName=ElementToFocus}" />
</Style>
控制标记:
<Button
x:Name="button_Clear"
Style="{DynamicResource Button_Reset}"
HorizontalAlignment="Right"
Content="Clear"
Command="{Binding Path=ClearCommand}"
ElementToFocus="textbox_SearchText"
Margin="0,0,0,7" />
我该如何做到这一点?
答案 0 :(得分:1)
我创建了一个附加行为,试图实现你想要做的事情。
附加行为代码:
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);
}
}
按钮的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>
基本上,我所做的是,
ElementToFocus
元素希望这有帮助。