【发布时间】:2020-12-14 01:31:40
【问题描述】:
我创建了一个简单的 Blend 行为以附加到 TextBox 元素。它的目的是在获得焦点时将文本框滚动到末尾,并在失去焦点时将其滚动回开头。
public class TextBoxScrollToEndBehaviour : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.GotFocus += AssociatedObject_GotFocus;
AssociatedObject.LostFocus += AssociatedObject_LostFocus;
}
private void AssociatedObject_LostFocus(object sender, System.Windows.RoutedEventArgs e)
{
var textBox = sender as TextBox;
textBox.ScrollToHorizontalOffset(0);
}
private void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
var textBox = sender as TextBox;
textBox.ScrollToHorizontalOffset(double.PositiveInfinity);
}
}
Xaml:
<TextBox Text="{Binding MyBinding, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Behaviors>
<behaviours:TextBoxScrollToEndBehaviour />
</i:Interaction.Behaviors>
</TextBox>
当我聚焦 TextBox 然后我单击其他一些控件以释放焦点时效果很好。问题是,如果我在共享相同行为的两个 TextBox 之间切换焦点,则第一个 TextBox 上的滚动不会设置回 0,即使在其上正确触发了 LostFocus 事件。
我在这里缺少什么?谢谢!
.NET 框架 4.7.2
【问题讨论】: