如何使用 MVVM 将焦点设置到文本框? [英] How to set focus to textbox using MVVM?

查看:35
本文介绍了如何使用 MVVM 将焦点设置到文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 ViewModel wpf 聚焦文本框?

How to focus a textbox from ViewModel wpf?

<TextBox Name="PropertySearch"
         Text="{Binding UpdateSourceTrigger=PropertyChanged, 
                        Mode=TwoWay, Path=PropertySearch, 
                        ValidatesOnDataErrors=True}"  
         Width="110" 
         Height="25" 
         Margin="10" />

推荐答案

您可以通过向您的 ViewModel 添加一个属性(或使用现有属性)来实现此目的,该属性指示何时应该发生 SetFocus 但实际上应该由 View 负责设置焦点,因为那纯粹是与视图相关的.

You can do this by adding a property to your ViewModel (or use an existing property) that indicates when the SetFocus should happen but the View should be responsible for actually setting the focus since that is purely View related.

您可以使用 DataTrigger 做到这一点.

You can do this with a DataTrigger.

查看:

<Grid Name="LayoutRoot" DataContext="{StaticResource MyViewModelInstance}">
    <Grid.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding UserShouldEditValueNow}" Value="True">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=PropertySearch}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>
    <TextBox   Name="PropertySearch"   Text="{Binding UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Path=PropertySearch, ValidatesOnDataErrors=True}" Width="110" Height="25" Margin="10" />
</Grid>

视图模型:

// When you think the view should set focus on a control
this.UserShouldEditValueNow = true;

仅使用布尔 ViewModel 属性UserShouldEditValueNow"简化了上面的示例.您可以将这样的属性添加到您的 ViewModel 或使用其他一些指示此状态的现有属性.

The example above is simplified by just using a boolean ViewModel property "UserShouldEditValueNow". You can add a property like this to your ViewModel or use some other exising property that indicates this state.

注意: 那么为什么在 MVVM 中这样做呢?一个原因是,假设 View 作者决定用 ComboBox 替换 TextBox,或者甚至更好,假设您的属性是一个整数值,它有一个 TextBox 来查看/编辑数字一个 Slider 作为另一种编辑相同值的方法,两个控件都绑定到相同的属性...... ViewModel 如何知道将焦点设置在哪个控件上?(当它甚至不应该首先知道绑定了什么控件或控件时)这样,视图可以通过更改 DataTrigger Setter 中的 ElementName 绑定目标来选择要聚焦的控件.

Note: So why is it done this way in MVVM? One reason is, suppose the View author decided to replace the TextBox with a ComboBox, or even better, suppose your property was an integer value that had both a TextBox to view/edit the number and a Slider as another way to edit the same value, both controls bound to the same property... how would the ViewModel know which control to set focus on? (when it shouldn't even know what control, or controls, are bound to it in the first place) This way the View can select which control to focus by changing the ElementName binding target in the DataTrigger Setter.

快乐编码!

这篇关于如何使用 MVVM 将焦点设置到文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆