我有一个TextBox
and a 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中。
The CompanyAssociation
是视图名称。
但光标没有被设置在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源代码调试,请参阅肖恩·布鲁克的 https://learn.microsoft.com/archive/blogs/sburke/configuring-visual-studio-to-debug-net-framework-source-code blog.
-
最后,我用来从 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.
}
}
}
现在,在您的视图(在 XAML 中)中,您可以将此属性绑定到您的 ViewModel:
<TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />
如果此答案没有帮助,请参阅答案#2。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)