如何使用另一个属性中的元素名称绑定样式中的行为

时间:2013-10-24 21:35:18

标签: wpf styles behavior wpf-4.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" />

我该如何做到这一点?

1 个答案:

答案 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>

基本上,我所做的是,

  1. 具有附加行为以存储要聚焦的元素
  2. 然后在附加的行为中添加事件处理程序以按下Click事件,
  3. Click活动中的
  4. 将焦点设置为ElementToFocus元素
  5. 希望这有帮助。