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

标签 c# wpf mvvm focus eventtrigger

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

像下面的例子:

<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 中)完成的事情,那也没关系。但我希望看到某种文档,说明它如何适合在 XAML 之外执行的 MVVM 模式。

最佳答案

您是否考虑过使用附加行为。它们易于实现和使用 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" />

关于c# - WPF - 单击按钮时设置焦点 - 无代码隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2204063/

相关文章:

c# - LINQ 条件求和

c# - 微软办公助手

c# - NHibernate 集合子查询

mvvm - Flipview 不更新 SelectedItem

WPF MVVM - 监控绑定(bind)对象的更改(例如,如果 IsDirty 则启用保存)

c# - 使用 SQL Server Compact 与专用 SQL Server 数据库的缺点

c# - 如何固定wpf窗口的高度和宽度

wpf - 使用 MVVM 模式单击项目时如何在 WPF 上下文菜单上获取 PlacementTarget

wpf - .Net Core 3.0 找不到 hostfxr.dll

c# - MVVM 中的 PasswordBox 绑定(bind)