【发布时间】:2016-06-23 10:11:31
【问题描述】:
当打开一个新窗口时,我想聚焦一个特定的文本框并选择其中的整个文本。 我在本教程的基础上进行了尝试:https://blogs.msdn.microsoft.com/argumentnullexceptionblogpost/2013/04/12/a-simple-selectall-behavior-for-textboxes/
为了聚焦元素,我在我的网格中使用了这个:
<Grid d:DataContext="{StaticResource DesignTimeLayerViewModel1}" FocusManager.FocusedElement="{Binding ElementName=LayerNameInput}">
并尝试了交互行为:
<TextBox x:Name="LayerNameInput"
Text="{Binding MapLayerName, UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
Width="240">
<i:Interaction.Behaviors>
<behaviors:SelectAllTextBoxBehavior></behaviors:SelectAllTextBoxBehavior>
</i:Interaction.Behaviors>
</TextBox>
行为代码:
public class SelectAllTextBoxBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.GotFocus += this.OnTextBoxGotFocus;
}
protected override void OnDetaching()
{
this.AssociatedObject.GotFocus -= this.OnTextBoxGotFocus;
base.OnDetaching();
}
private void OnTextBoxGotFocus(object sender, RoutedEventArgs e)
{
this.AssociatedObject.SelectAll();
}
}
问题在于绑定。创建窗口时,行为正确触发,但实际上 TextBox 中没有文本。然后初始化 TextBox 并将文本设置为绑定变量的值,并且选择丢失。 如果我通过多次使用 Tab 重新调整 TextBox 的焦点,它工作正常。
如何在创建窗口时聚焦 TextBox 并选择其整个文本?背后没有大量代码?
提前致谢!
【问题讨论】: