我可以在TextBox中使用自定义形状而不是默认边框吗?

时间:2016-03-20 04:26:54

标签: c# wpf xaml textbox shapes

我想要一个带有自定义形状的文本框,如椭圆形或三角形边框而不是矩形......是否可能?

1 个答案:

答案 0 :(得分:1)

是的,您可以更改控件的Style以符合您的需求。

    <Style x:Key="TextBox.Ellipse" TargetType="{x:Type TextBox}">
        <!--Here you can set the default properties of this style.-->
        <Setter Property="FontWeight" Value="Bold"/>

        <!--You can change the shape of the control by setting the template-->
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <Ellipse x:Name="Border" Stroke="#FF393785" StrokeThickness="2">
                            <Ellipse.Fill>
                                <RadialGradientBrush GradientOrigin="0.25,0.25" 
                                                     RadiusY="0.75" RadiusX="0.75">
                                    <GradientStop Color="White" Offset="0.2"/>
                                    <GradientStop Color="#FF2EC452" Offset="0.5"/>
                                    <GradientStop Color="#FF606060" Offset="1"/>
                                </RadialGradientBrush>
                            </Ellipse.Fill>
                            </Ellipse>                              
                        <!-- The implementation places the Content into the ScrollViewer. 
                             It must be named PART_ContentHost 
                             for the control to function -->
                        <ScrollViewer x:Name="PART_ContentHost" Background="Transparent"
                            HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Fill" Value="#000" TargetName="Border"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style> 

将此Style放在资源字典中,例如App.Xaml等 然后你可以像这样设置TextBox的样式:

<TextBox Style="{StaticResource TextBox.Ellipse}" />