让我分三个部分回答您的问题。
我想知道您的示例中的“ cs.txtCompanyID”是什么?它是TextBox控件吗?如果是,则说明您的方法错误。一般来说,在ViewModel中对UI进行任何引用不是一个好主意。您可以问“为什么?” 但这是在Stackoverflow上发布的另一个问题:)。
跟踪Focus问题的最佳方法是…调试.Net源代码。别开玩笑了 它节省了我很多时间。要启用.net源代码调试,请参阅Shawn Bruke的博客。
最后,我用来从ViewModel设置焦点的一般方法是附加属性。我写了非常简单的附加属性,可以在任何UIElement上进行设置。例如,它可以绑定到ViewModel的属性“ IsFocused”。这里是:
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool) obj.GetValue(IsFocusedProperty);
}public static void SetIsFocused(DependencyObject obj, bool value){ obj.SetValue(IsFocusedProperty, value);}public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof (bool), typeof (FocusExtension), new UIPropertymetadata(false, OnIsFocusedPropertyChanged));private static void onIsFocusedPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e){ var uie = (UIElement) d; if ((bool) e.NewValue) { uie.Focus(); // Don't care about false values. }}}
现在,在您的View(在XAML中)中,您可以将此属性绑定到您的ViewModel:
<TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />希望这可以帮助 :)。如果不是,请参考答案2。
干杯。



