WPF MVVM Default Focus on Textbox和selectAll [英] WPF MVVM Default Focus on Textbox and selectAll

查看:732
本文介绍了WPF MVVM Default Focus on Textbox和selectAll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的情况,我有两个使用MVVM模式开发的WPF表单。第二个表单将从第一个打开(form1将在后端,直到form2关闭),关闭第二个表单激活。 p>

现在我想在form1上设置默认焦点的文本框。我能够用FocusManager做到这一点,而且它的工作正常,但是当我从form2进入form1的时候,这同样不能正常工作。同样在这段时间,我必须把焦点放在默认的文本框上,而且我还需要选择它上面的所有文本。



任何建议对我都有很大的帮助。



问候,

克里希纳

解决方案

UI元素使用 FocusManager.FocusedElement 附加属性

 < Grid FocusManager.FocusedElement ={Binding ElementName = SomeTextBox}> 
< TextBox Name =SomeTextBoxText ={Binding SomeProperty}/>
< / Grid>

这个应该选择 TextBox 每次加载视图/ UserControl



至于如何从视图中选择文本模型...解决方案将是相同的处理任何事件时使用MVVM。将其包装在附加属性中。请注意,处理视图模型中的所有事件是不合适的,因为它不应该真正了解纯粹的UI事件。但是,选择是你的。

为了换行,或者处理附加属性中的任何事件,你基本上声明了一个扩展 DependencyObject 类并定义一个或多个静态属性。而不是一遍又一遍地讲完整个故事,我宁愿引导你回答我对

有关附加属性的背景信息,请参阅附加属性概述页面。


I have situation like this, I have 2 WPF forms developed using MVVM Pattern ..2nd form will be opened from first(form1 will be in backend till form2 is closed) and closing the second makes the first form active.

Now I want to make a textbox on form1 with default focus set on it. I was able to do it with FocusManager and its working fine but the same is not working fine when Im getting into form1 from form2. Also during this time I have to set the focus on the default textbox and also I need to select all the text present on it. I am unable to understand how to do this with viewmodel.

Any suggestions will be of great help for me.

Regards,

Krishna

解决方案

You can focus a particular UI element using the FocusManager.FocusedElement Attached Property:

<Grid FocusManager.FocusedElement="{Binding ElementName=SomeTextBox}">
    <TextBox Name="SomeTextBox" Text="{Binding SomeProperty}" />
</Grid>

This should select the TextBox each time the view/UserControl is loaded.

As for how to select text from the view model... the solution would be the same to handle any event when using MVVM. Wrap it in an Attached Property. Please beware that it is not appropriate to handle all events in the view model, as it should not really have any knowledge of purely UI events. However, the choice is yours.

To 'wrap', or handle any event in an Attached Property, you basically declare a class that extends the DependencyObject class and define one or more static properties. Rather than go over the whole story once again, I'd prefer to direct you to my answer to the What's the best way to pass event to ViewModel? question on Stack Overflow, which provides further links and a full code example.

For background information on Attached Properties, please see the Attached Properties Overview page on MSDN.

这篇关于WPF MVVM Default Focus on Textbox和selectAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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