wpf 文本框平面边框样式

问题描述:

需要为基于 wpf 的文本框设置扁平边框样式...真的很惊讶地发现没有简单的方法可以像在 winforms 文本框 BorderStyle.FixedSingle 中那样获得这种样式

need to have flat border style for wpf based textbox... really surprised to see there is no easy way to get this like was in winforms textbox BorderStyle.FixedSingle

有没有什么简单的方法可以为 wpf 文本框完成此操作

is there any easy way to get this done for wpf textbox

这样做的方法是使用控件模板自己绘制边框.您可以通过多种不同的方式执行此操作,这里有几种方式供您查看.

The way to do this is to use a control template to draw the border yourself. You can do this in many different ways, heres a couple for you to look at.

快速破解方法:

<TextBox>
    <TextBox.Template>
        <ControlTemplate TargetType="{x:Type TextBox}">
            <Grid>
                <Rectangle  Stroke="{StaticResource ResourceKey=detailMarkBrush}" StrokeThickness="1"/>
                <TextBox Margin="1" Text="{TemplateBinding Text}" BorderThickness="0"/>
            </Grid>
        </ControlTemplate>
    </TextBox.Template>
</TextBox>

然后使用资源...

<ResourceDictionary>
    <Color x:Key="detailMark">#FFA1A9B3</Color>
    <SolidColorBrush x:Key="detailMarkBrush" Color="{StaticResource ResourceKey=detailMark}" />
    <Style x:Key="flatTextBox" TargetType="{x:Type TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <Rectangle  Stroke="{StaticResource ResourceKey=detailMarkBrush}" StrokeThickness="1"/>
                        <TextBox Margin="1" Text="{TemplateBinding Text}" BorderThickness="0"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

然后你可以使用样式:

<TextBox Style="{StaticResource ResourceKey=flatTextBox}" />