WPF - 单击按钮时设置焦点 - 无代码隐藏

2024-04-26

有没有办法设置Focus使用 WPF 从一个控件到另一个控件Triggers?

就像下面的例子:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>  
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
      <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBox Name="txtName"></TextBox>    
    <TextBox Grid.Row="1" Name="txtAddress"></TextBox>
    <Button Grid.Row="2" Content="Finish">
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">

                <!-- Insert cool code here-->  

            </EventTrigger>
        </Button.Triggers>
    </Button>
  </Grid>
</Page>

有没有办法解决这个问题EventTrigger将焦点放在文本框“txtName”上?

我正在尝试使用严格的 MVVM 来找到执行此类操作的方法。如果这是不应该通过 XAML(在 MVVM 中)完成的事情,那么也没关系。但我希望看到一些关于它如何适应 MVVM 模式并在 XAML 之外执行此操作的文档。


您是否考虑过使用附加行为。它们很容易实现和使用 AttachedProperty。尽管它仍然需要代码,但该代码被抽象到类中并可以重用。它们可以消除“代码隐藏”的需要,并且通常与 MVVM 模式一起使用。

尝试一下这个,看看它是否适合你。

public class EventFocusAttachment
{
    public static Control GetElementToFocus(Button button)
    {
        return (Control)button.GetValue(ElementToFocusProperty);
    }

    public static void SetElementToFocus(Button button, Control value)
    {
        button.SetValue(ElementToFocusProperty, value);
    }

    public static readonly DependencyProperty ElementToFocusProperty =
        DependencyProperty.RegisterAttached("ElementToFocus", typeof(Control), 
        typeof(EventFocusAttachment), new UIPropertyMetadata(null, ElementToFocusPropertyChanged));

    public static void ElementToFocusPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var button = sender as Button;
        if (button != null)
        {
            button.Click += (s, args) =>
                {
                    Control control = GetElementToFocus(button);
                    if (control != null)
                    {
                        control.Focus();
                    }
                };
        }
    }
}

然后在你的 XAML 中做一些类似的事情......

<Button 
    Content="Click Me!" 
    local:EventFocusAttachment.ElementToFocus="{Binding ElementName=textBox}" 
    />
<TextBox x:Name="textBox" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF - 单击按钮时设置焦点 - 无代码隐藏 的相关文章

随机推荐