【发布时间】:2019-12-29 12:23:53
【问题描述】:
我正在尝试制作一个文本框,每当任何新字符出现/消失时,它都会以某种方式突出显示(例如,字符以黄色到黑色的字体颜色渐变出现,...)。 就我而言,当我在第一个文本框中编写文本时,我希望只有第二个文本框中的新字符出现时才会突出显示。最后,我需要将两个文本逐个字符对齐。
不幸的是,文本框文本属性仅被视为整个字符串的一个属性,因此当我尝试在 TextBox.TextChanged 事件之后添加动画时,每次击键后整个文本都会淡入淡出。我唯一的想法是编写一些适配器,它将第二个文本框中的字符串转换为标签集合,其中每个标签都可以充当单个字符,因此可以在选定的单个标签(字符)上执行突出显示动画。
这是我项目的一个最小子问题,它是使用 MVVM 模式编写的。所以理想情况下,我正在寻找 xaml 中的解决方案,但我也对任何黑客解决方案持开放态度,因为文本框中的字符不是为动画而设计的。
在这里,我包含一个代码来重现示例中的窗口。
主窗口
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AnimatedTextBoxStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
<local:AnimatedTextBoxViewModel x:Key="ViewModel"/>
</ResourceDictionary>
</Window.Resources>
<StackPanel DataContext="{StaticResource ViewModel}" Margin="5,5,5,5">
<TextBox Margin="0,0,0,2"
Style="{StaticResource ResourceKey=AnimatedTextBoxStyle}"
Text="{Binding SomeText,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay}">
</TextBox>
<TextBox IsEnabled="False"
Style="{StaticResource ResourceKey=AnimatedTextBoxStyle}"
Text="{Binding SomeText}">
</TextBox>
</StackPanel>
AnimatedTextBoxStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TextBoxCharsAnimation">
<Style x:Key="AnimatedTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="FontFamily" Value="Consolas"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Height" Value="26"/>
<Style.Triggers>
<EventTrigger RoutedEvent="TextBox.TextChanged">
<!-- Maybe begin storyboard here? -->
</EventTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
AnimatedTextBoxViewModel.cs
using TextBoxCharsAnimation.Support;
namespace TextBoxCharsAnimation
{
class AnimatedTextBoxViewModel : ViewModelBase
{
private string _someText = "";
public string SomeText
{
get => _someText;
set
{
_someText = value;
OnPropertyChanged();
}
}
}
}
【问题讨论】:
-
您可以使用 texteffect 分别为每个角色设置动画。我相当肯定这包括颜色。 joshsmithonwpf.wordpress.com/2007/08/13/animating-text-in-wpf 您(显然)还必须在添加新角色时进行计算,以便仅在该角色上开始动画。还。 books.google.co.uk/…
标签: wpf xaml animation textbox