我正在尝试在我的下一个 WP7 应用程序(用 Vb.NET 编写)中提高我的 MVVM 能力。我有一个已获得焦点并显示 WP7 键盘的文本框。我正在使用命令绑定(bind)和 xyzzer 的可绑定(bind)应用程序栏(非常好)。
http://bindableapplicationb.codeplex.com/
我希望能够通过在表单上设置焦点来从 ViewModel 中取消 TextBox 的焦点。通常(非 MVVM)我会通过调用从表单中执行此操作:
Me.Focus()
但我不能从 ViewModel 做到这一点(我不应该这样做)。目前,我正在从 ViewModel 中提出一个事件并将其捕获到表单上,但它很讨厌。是否有一种 MVVM 友好的方式来做到这一点?到目前为止,我还没有使用过工具包,因为 vb.net 中的示例有限。
我一直在使用命令绑定(bind)。
最佳答案
您可以尝试使用一种行为:
public class FocusBehavior : Behavior<Control>
{
protected override void OnAttached()
{
AssociatedObject.GotFocus += (sender, args) => IsFocused = true;
AssociatedObject.LostFocus += (sender, a) => IsFocused = false;
AssociatedObject.Loaded += (o, a) => { if (HasInitialFocus || IsFocused) AssociatedObject.Focus(); };
base.OnAttached();
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.Register(
"IsFocused",
typeof (bool),
typeof (FocusBehavior),
new PropertyMetadata(false, (d, e) => { if ((bool) e.NewValue) ((FocusBehavior) d).AssociatedObject.Focus(); }));
public bool IsFocused
{
get { return (bool) GetValue(IsFocusedProperty); }
set { SetValue(IsFocusedProperty, value); }
}
public static readonly DependencyProperty HasInitialFocusProperty =
DependencyProperty.Register(
"HasInitialFocus",
typeof (bool),
typeof (FocusBehavior),
new PropertyMetadata(false, null));
public bool HasInitialFocus
{
get { return (bool) GetValue(HasInitialFocusProperty); }
set { SetValue(HasInitialFocusProperty, value); }
}
}
然后在 xaml 中:
<TextBox>
<i:Interaction.Behaviors>
<behaviors:FocusBehavior HasInitialFocus="True"
IsFocused="{Binding IsFocused}" />
</i:Interaction.Behaviors>
</TextBox>
关于vb.net - WP7 MVVM 如何从 ViewModel 调用 me.setfocus()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166219/