美化WPF中TextBox的Style样式

这篇博客详细介绍了如何使用XAML修改TextBox控件的样式和模板,包括设置边框颜色、鼠标悬停和焦点时的效果,并通过HeightToCornerConverter实现边框圆角与控件高度的自适应。此外,还展示了ScrollViewer的自定义模板,以及在不同状态下的触发器行为。最终实现了美观且功能完整的输入框设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最后项目中美工给出了一套设计方案,需要修改Textbox控件的样式,于是修改一下默认的样式和模板

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:converter="clr-namespace:IVF.Converter">
    <!--for TextboxDictionary.xaml Border CornerRadius-->
    <converter:HeightToCornerConverter x:Key="HeightToCornerConverter" />

    <SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
    <SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/>
    <SolidColorBrush x:Key="TextBox.Focus.Border" Color="#7278FB"/>
    <Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
        <Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border CornerRadius="{TemplateBinding Height,Converter={StaticResource HeightToCornerConverter}}" x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" Template="{DynamicResource ScrollViewerControlTemplate}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}"/>
                            <Setter Property="BorderThickness" TargetName="border" Value="4"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
                    <Condition Property="IsSelectionActive" Value="false"/>
                </MultiTrigger.Conditions>
                <Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
            </MultiTrigger>
        </Style.Triggers>
    </Style>
    <ControlTemplate x:Key="ScrollViewerControlTemplate" TargetType="{x:Type ScrollViewer}">
        <Grid x:Name="Grid" Background="{TemplateBinding Background}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Rectangle x:Name="Corner" Grid.Column="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Grid.Row="1"/>
            <ScrollContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" CanHorizontallyScroll="False" CanVerticallyScroll="False" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="0" Margin="{TemplateBinding Padding}" Grid.Row="0"/>
            <ScrollBar x:Name="PART_VerticalScrollBar" AutomationProperties.AutomationId="VerticalScrollBar" Cursor="Arrow" Grid.Column="1" Maximum="{TemplateBinding ScrollableHeight}" Minimum="0" Grid.Row="0" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}"/>
            <ScrollBar x:Name="PART_HorizontalScrollBar" AutomationProperties.AutomationId="HorizontalScrollBar" Cursor="Arrow" Grid.Column="0" Maximum="{TemplateBinding ScrollableWidth}" Minimum="0" Orientation="Horizontal" Grid.Row="1" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}"/>
        </Grid>
    </ControlTemplate>

    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBoxStyle}"/>
</ResourceDictionary>

注意这里有一个HeightToCornerConverter转换器,因为border的圆角和textbox的height成2倍的关系,需要自适应转换,所有在用的时候要注意实例化这个类。
最后的效果如下
在这里插入图片描述

### WPF TextBox 控件的美化方法 #### 使用样式自定义外观 可以通过创建 `Style` 来改变 `TextBox` 的默认视觉效果。下面是一个简单的例子,展示了如何通过设置不同的属性来定制 `TextBox`: ```xml <Window.Resources> <Style TargetType="TextBox" x:Key="CustomTextBoxStyle"> <Setter Property="BorderThickness" Value="2"/> <Setter Property="BorderBrush" Value="#FF7F50"/> <!-- 橙红色边框 --> <Setter Property="Background" Value="#ECECFF"/> <!-- 浅蓝色背景 --> <Setter Property="Foreground" Value="#3D3D3D"/> <!-- 深灰色文字颜色 --> <Setter Property="FontFamily" Value="Arial"/> <Setter Property="FontSize" Value="14"/> <Setter Property="Padding" Value="8,4"/> <Setter Property="Margin" Value="10"/> </Style> </Window.Resources> <!-- 应用样式到具体的 TextBox 实例 --> <TextBox Style="{StaticResource CustomTextBoxStyle}" Width="200" Height="30"/> ``` 此代码片段设置了多个属性以增强用户体验并使界面更加美观[^2]。 #### 利用触发器动态调整样式 除了静态设定外,还可以利用 `Trigger` 或者 `EventTrigger` 动态响应某些条件下的变化而更新 UI 表现形式。例如,在获得焦点时更改边框的颜色: ```xml <Style TargetType="TextBox" x:Key="FocusBorderStyle"> <Setter Property="BorderBrush" Value="Silver"/> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="BorderBrush" Value="DodgerBlue"/> </Trigger> </Style.Triggers> </Style> ``` 这段配置会在 `TextBox` 获得键盘输入焦点的时候将其边框变为天蓝色。 #### 结合模板深入定制布局结构 对于更复杂的场景,则可能需要用到控件模板 (`ControlTemplate`) 对整个组件内部元素进行重构重组。不过这通常涉及到更多细节层面的知识和技术实现,适用于有经验开发者做高级优化或特殊需求处理[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值