我想知道是否可以制作一个可写入文本的TextBox或任何控件,使其像Word 2013一样,动画体验非常好。
目前我已经能够对控件本身(如TextBox等)进行此类型的动画,但是要对光标或文本本身执行此类型的动画则是新的挑战。
<UserControl
x:Class="YourNamespace.AnimatedCursorTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="23"
d:DesignWidth="300"
xmlns:c="clr-namespace:System.Windows.Controls;assembly=PresentationFramework"
Name="Control">
<UserControl.Resources>
<c:BooleanToVisibilityConverter
x:Key="BoolToVisibility" />
</UserControl.Resources>
<Grid>
<TextBox
Name="MainTextBox"
CaretBrush="Transparent"
SelectionChanged="MainTextBox_SelectionChanged"
TextChanged="MainTextBox_TextChanged"
GotKeyboardFocus="MainTextBox_GotKeyboardFocus" />
<Canvas
Visibility="{Binding IsKeyboardFocusWithin,
ElementName=Control,
Converter={StaticResource BoolToVisibility}}"
Height="{Binding ActualHeight, ElementName=MainTextBox}"
Width="{Binding ActualWidth, ElementName=MainTextBox}">
<Rectangle
HorizontalAlignment="Left"
Name="Caret"
Width="1"
Fill="Black" />
</Canvas>
</Grid>
</UserControl>
代码后台:
public partial class AnimatedCursorTextBox : UserControl
{
private DoubleAnimation cursorAnimation = new DoubleAnimation();
public AnimatedCursorTextBox()
{
InitializeComponent();
}
private void UpdateCaretPosition()
{
var rectangle = MainTextBox.GetRectFromCharacterIndex(MainTextBox.CaretIndex);
Caret.Height = rectangle.Bottom - rectangle.Top;
Canvas.SetTop(Caret, rectangle.Top);
Canvas.SetBottom(Caret, rectangle.Bottom);
var left = Canvas.GetLeft(Caret);
if (!double.IsNaN(left))
{
cursorAnimation.From = left;
cursorAnimation.To = rectangle.Right;
cursorAnimation.Duration = new Duration(TimeSpan.FromSeconds(.05));
Caret.BeginAnimation(Canvas.LeftProperty, cursorAnimation);
}
else
{
Canvas.SetLeft(Caret, rectangle.Right);
}
}
private void MainTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
UpdateCaretPosition();
}
private void MainTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
UpdateCaretPosition();
}
private void MainTextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
UpdateCaretPosition();
}
}
TextBox
中的Animation
受到开发者的限制。例如,文本属性不是依赖属性,所以动画无法涉及它。另一方面,在MS Office中工作时,希望能够正常实现。因此有解决方案的希望...但是在什么方面呢? - Anatoliy Nikolaev