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

查看:384
本文介绍了如何使用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应该真正负责设置焦点,因为那完全与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>

ViewModel:

ViewModel:

// 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中这样做呢?原因之一是,假设视图作者决定用ComboBox替换TextBox,或者甚至更好,假设您的属性是一个整数值,同时具有一个TextBox来查看/编辑数字一个Slider,如下所示:另一种编辑相同值的方法,两个控件都绑定到相同的属性... ViewModel如何知道要设置焦点的控件? (当它甚至根本不知道要绑定哪个控件时,)通过这种方式,View可以通过更改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天全站免登陆