使用MVVM在WPF中设置焦点

本文关键字:设置 焦点 WPF MVVM 使用 | 更新日期: 2023-09-27 18:03:36

我有多个文本框的网格。根据用户可能采取的操作,应该将焦点更改为其中一个文本框。我目前的解决方案使用ViewModel中的字符串属性和xaml中的数据触发器来更改焦点。它工作得很好,但它似乎是一个相当迂回的方式来实现这一点,所以我想知道它是否可以在一个更明确的方式?

    <Grid.Style>
        <Style TargetType="Grid">
            <Style.Triggers>
                <DataTrigger Binding="{Binding FocusedItem}" Value="number">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=number}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedItem}" Value="name">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=name}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding FocusedItem}" Value="id">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=id}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>

正如你所看到的,属性的值和元素的名字是一样的,所以我想用一个触发器来做这件事,而不是每个元素都有一个触发器。

也许有人能想出一个更干净的方法?

Thanks in advance

使用MVVM在WPF中设置焦点

我在我的一个项目中处理设置焦点的方式是使用焦点扩展(我很抱歉我不记得我在哪里看到这是来自原始帖子)。

    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
           return (bool)obj.GetValue(IsFocusedProperty);
        }

        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }

        public static readonly DependencyProperty IsFocusedProperty =
                DependencyProperty.RegisterAttached(
                 "IsFocused", typeof(bool), typeof(FocusExtension),
                 new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

        private static void OnIsFocusedPropertyChanged(DependencyObject d,
                DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                uie.Focus();
            }
        }
    }

然后在xaml文件中我使用它作为依赖属性:

<TextBox Uid="TB1" FontSize="13" localExtensions:FocusExtension.IsFocused="{Binding Path=TB1Focus}" Height="24" HorizontalAlignment="Left" Margin="113,56,0,0" Name="TB_UserName" VerticalAlignment="Top" Width="165" Text="{Binding Path=TB1Value, UpdateSourceTrigger=PropertyChanged}" />

你可以使用一个绑定来设置焦点