0

我想将焦点行为绑定到重置按钮,该按钮将焦点放在 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" />

我怎样才能做到这一点?

4

1 回答 1

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);
        }
    }

以及 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>

基本上,我所做的是,

  1. 有一个附加的行为来存储要聚焦的元素,
  2. 然后在附加的行为中将事件处理程序添加到按钮 Click 事件,
  3. 在 Click 事件中将焦点设置在ElementToFocus元素上

希望这可以帮助。

于 2013-10-29T18:20:21.347 回答