所以基本上我想实现悬停效果,该效果是文本框底部出现一条线,该线的宽度必须是文本框实际宽度的一半。
如果可能的话,我想要一个动画,也许是一个颜色动画,它的颜色会逐渐从透明变为纯色。我还想指定我的 TextBox 是带水印的 TextBox。
<Style TargetType="{x:Type local:TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TextBox}">
<DockPanel HorizontalAlignment="Stretch">
<Border CornerRadius="10" BorderBrush="{StaticResource BackgroundColor}" BorderThickness="1" Background="{StaticResource BackgroundColor}">
<Grid Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}">
<TextBox Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}" VerticalAlignment="Center" Foreground="{StaticResource TextColor}" Background="{StaticResource BackgroundColor}" Padding="10" HorizontalAlignment="Left" x:Name="SearchTermTextBox" Margin="5" BorderThickness="0"/>
<TextBlock IsHitTestVisible="False" Text="Enter Search Term Here" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="20,0,0,0" Foreground="{StaticResource TextColor}" Background="{StaticResource BackgroundColor}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=SearchTermTextBox}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
TextBox
是一个 Control
,因此它可以像其他任何模板一样重新模板化。诀窍是确保有一个名为 PART_ContentHost
的子元素 - 通常是 ScrollViewer
- 控件将使用它来呈现可编辑文本。 (有关更多详细信息,请参阅TextBox 的 WPF 默认样式和模板文档)。
这是一个简单的示例,它将在悬停时显示下划线,并以 0.25 秒的淡入/淡出效果。您应该能够进一步调整它以获得您想要的外观/行为。并且不要忘记,您始终可以对
TextBox
进行子类化以添加更多 DependencyProperty
,以增加外观的粒度。
<Style x:Key="ResponsiveTextBoxStyle"
TargetType="TextBox"
BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="BorderBrush"
Value="Blue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="Underline"
Storyboard.TargetProperty="(Border.Opacity)"
To="0"
Duration="0:00:00.25" />
</Storyboard>
</VisualState>
<VisualState x:Name="MouseOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="Underline"
Storyboard.TargetProperty="(Border.Opacity)"
To="1"
Duration="0:00:00.25" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ScrollViewer Margin="0"
Grid.Row="0"
x:Name="PART_ContentHost" />
<Border x:Name="Underline"
Grid.Row="1"
Opacity="0"
BorderThickness="1"
Height="2"
BorderBrush="{TemplateBinding BorderBrush}"
Margin="25 0 25 0" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>