![](/img/trans.png)
[英]How to set the focus on a TextBox in the ViewModel (WPF/MVVM)?
[英]wpf MVVM Focus cursor on textbox
在WPF窗口中,我尝试默认将光标放在文本框之一上。 阅读一些问题和答案后,我尝试了以下操作:
xaml:
<StackPanel Grid.Row="1"
<StackPanel.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding UserShouldEditValueNow}" Value="true">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=FID}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<TextBox Name ="FID" Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}"
FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
</StackPanel>
CS :(视图模型)
this.UserShouldEditValueNow = true;
我希望在打开窗口时在文本框FID上看到闪烁的光标。 但是,此文本框上根本没有光标。 调试显示我正在遍历CS代码,将该值设置为true。 有什么想法吗?
解决方案涉及:1.添加FocusExtension类。 2. Focus和Keyboard.Focus位于Dispatcher.BeginInvoke中
CS。
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.Dispatcher.BeginInvoke(
new Action(
delegate{
uie.Focus();
Keyboard.Focus(uie);
}
)
);
}
}
}
.xaml
<TextBox Text="{Binding FixID, UpdateSourceTrigger=PropertyChanged}" viewModels:FocusExtension.IsFocused="{Binding UserShouldEditValueNow}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.