WPF MVVM聚焦场对负载 [英] WPF MVVM Focus Field on Load

查看:85
本文介绍了WPF MVVM聚焦场对负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了一个文本框和几个按钮 S下来看。当窗口加载我想要的文本框有焦点。

I have a View that has a single TextBox and a couple Buttons below it. When the window loads I want that TextBox to have focus.

如果我没有使用MVVM,我只想叫 TextBox.Focus()在Loaded事件。 ?可是我的视图模型不知道我的看法,所以我怎么能做到这一点不把代码放到我的看法的代码隐藏

If I was not using MVVM I would just call TextBox.Focus() in the Loaded event. However my ViewModel does not know about my view so how can I accomplish this without putting code into the codebehind of my view?

编辑:
读取应答后我决定把这个代码视图中的XAML

After reading the answers I decided to put this code in the view xaml

<DockPanel FocusManager.FocusedElement="{Binding ElementName=MessageTextBox}">    
    <TextBox Name="MessageTextBox" Text="{Binding Message}"/>
</DockPanel>

如果这个比初始页面焦点等我可能会建议乔恩·加洛韦的回答什么,因为它可以控制从视图模型。

If this were anything other than initial page focus I would probably recommend Jon Galloway's answer since it can be controlled from the ViewModel.

推荐答案

如果它让你感觉更好(这让我感觉更好),你可以使用在XAML中做到这一点附加属性:

If it makes you feel better (it makes me feel better) you can do this in Xaml using an attached property:

http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx

任何你在代码隐藏你可以在XAML做,如果你知道的技巧。幸运的是,你没有实现这一招 - MS这样做是为了你。

Anything you can do in codebehind you can do in Xaml if you know the tricks. Fortunately, you didn't have to implement this trick - MS did it for you.

这篇关于WPF MVVM聚焦场对负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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