我的 View 中有一个 TextBox
和一个 Button
。
现在我在单击按钮时检查条件,如果条件结果为假,则向用户显示消息,然后我必须将光标设置到 TextBox
控件。
if (companyref == null)
{
var cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation();
MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK,
MessageBoxImage.Exclamation);
cs.txtCompanyID.Focusable = true;
System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);
}
以上代码在ViewModel中。
CompanyAssociation
是 View 名称。
但是 TextBox
中没有设置光标。
xaml 是:
<igEditors:XamTextEditor Name="txtCompanyID"
KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown"
ValueChanged="txtCompanyID_ValueChanged"
Text="{Binding Company.CompanyId,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
Width="{Binding ActualWidth, ElementName=border}"
Grid.Column="1" Grid.Row="0"
VerticalAlignment="Top"
HorizontalAlignment="Stretch"
Margin="0,5,0,0"
IsEnabled="{Binding Path=IsEditable}"/>
<Button Template="{StaticResource buttonTemp1}"
Command="{Binding ContactCommand}"
CommandParameter="searchCompany"
Content="Search"
Width="80"
Grid.Row="0" Grid.Column="2"
VerticalAlignment="Top"
Margin="0"
HorizontalAlignment="Left"
IsEnabled="{Binding Path=IsEditable}"/>
最佳答案
让我分三部分回答你的问题。
我想知道您示例中的“cs.txtCompanyID”是什么?它是一个文本框控件吗?如果是,那么你走错了路。一般来说,在 ViewModel 中引用 UI 并不是一个好主意。你可以问“为什么?”但这是要在 Stackoverflow 上发布的另一个问题 :)。
跟踪 Focus 问题的最佳方法是...调试 .Net 源代码。别开玩笑了。它多次为我节省了很多时间。要启用 .net 源代码调试,请参阅 Shawn Bruke's博客。
最后,我用来从 ViewModel 设置焦点的一般方法是附加属性。我写了非常简单的附加属性,可以在任何 UIElement 上设置。例如,它可以绑定(bind)到 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 中)您可以将此属性绑定(bind)到您的 ViewModel:
<TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />
希望这对您有所帮助 :)。如果它没有提到答案#2。
干杯。
关于c# - 从 View 模型将焦点设置在 WPF 中的 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1356045/