完全通过Xaml代码实现,使用了UserControl进行封装。功能包括聚焦时控件展开,输入为空时的文字提示,以及待选提示项列表等效果。实现效果如下图:
xaml代码
<UserControl x:Class="SearchBar.SearchBox"
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"
xmlns:local="clr-namespace:SearchBar"
UseLayoutRounding="True"
TextElement.FontSize="14"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="440">
<UserControl.Resources>
<SolidColorBrush x:Key="Control.BoderBrush" Color="#CBCBCB"/>
<Style TargetType="{x:Type TextBox}">
"Background" Value="#FFF2F3F4"/>
"BorderBrush" Value="{StaticResource Control.BoderBrush}"/>
"Foreground" Value="#515151"/>
"VerticalContentAlignment" Value="Center"/>
"Padding" Value="8 0 0 0"/>
"BorderThickness" Value="1"/>
"KeyboardNavigation.TabNavigation" Value="None"/>
"HorizontalContentAlignment" Value="Left"/>
"AllowDrop" Value="true"/>
"ScrollViewer.PanningMode" Value="VerticalFirst"/>
"Stylus.IsFlicksEnabled" Value="False"/>
"Template">
"{x:Type TextBox}">
x:Name="border" CornerRadius="8" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
"44"/>
x:Name="bdLeft" CornerRadius="8" Margin="4 4 8 4">
x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
"输入搜索内容" VerticalAlignment="Center" Margin="10 0" Opacity="0.8">