WPF 自定义搜索框
1.首先看看效果
2.首先定义静态资源
<UserControl.Resources> <ControlTemplate TargetType="{x:Type TextBox}" x:Key="SearchTextBoxTemplate"> <Border x:Name="border" BorderThickness="1" Background="Transparent" SnapsToDevicePixels="True" BorderBrush="Gray" CornerRadius="10"> <Grid Background="Transparent" Margin="1" > <Grid.ColumnDefinitions> <!--<ColumnDefinition Width="30"/>--> <ColumnDefinition/> <ColumnDefinition Width="40"/> </Grid.ColumnDefinitions> <TextBlock x:Name="mt" Text="请输入搜索内容" Grid.Column="0" Visibility="Collapsed" VerticalAlignment="Center" Foreground="Gray" Margin="10 0 0 0"/> <Button Grid.Column="1" Content="🔍" FontFamily="Fonts/#iconfont" FontSize="16" x:Name="btn" Click="btn_Click"> <Button.Resources> <Style TargetType="Button"> <Setter Property="Foreground" Value="White"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="Background" Value="#FF4D4D"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border x:Name="border" Background="{TemplateBinding Background}" CornerRadius="0 10 10 0" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True"> <TextBlock Text="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" VerticalAlignment="Center" HorizontalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Button.Resources> </Button> <ScrollViewer x:Name="PART_ContentHost" Grid.Column="0" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" Margin="10 0 0 0" Background="Transparent" VerticalAlignment="Center"/> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Opacity" TargetName="border" Value="0.56"/> </Trigger> <DataTrigger Binding="{Binding Text,RelativeSource={RelativeSource Mode=Self}}" Value=""> <Setter TargetName="mt" Property="Visibility" Value="Visible"/> <Setter TargetName="btn" Property="Background" Value="#C9C6C6"/> <Setter TargetName="btn" Property="Foreground" Value="Gray"/> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </UserControl.Resources>
3.调用
<TextBox x:Name="SearchBox" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300" Height="32" Margin="5" Template="{StaticResource SearchTextBoxTemplate}" Text="{Binding SearchText}" Foreground="#3E3E42"/>