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



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

我怎样才能做到这一点?

我创建了一个附加行为来尝试实现您要做的事情。

附加的行为代码:

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=.}" />

来自我的主窗口的示例代码:

<StackPanel>
        <TextBox Name="TextBoxOne" />
        <TextBox Name="TextBoxTwo" />
        <TextBox Name="TextBoxThree" />
        <Button Content="Reset" local:ElementFocusBehavior.ElementToFocus="{Binding ElementName=TextBoxThree, Path=.}" />
    </StackPanel>

基本上,我所做的是,

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

希望这有帮助。

相关内容

  • 没有找到相关文章

最新更新