wpf textbox flat border style

2020-07-01 09:52发布

问题:

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

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

回答1:

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.

The quick hack approach:

<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>

and then theres using resources...

<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>

and then you can use the style:

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


回答2:

<TextBox BorderThickness="1" BorderBrush="Black">

just try this by black or gray



回答3:

This is better way to me, make a custom template with border, to override the default one.

And most important make ScrollViewer named PART_ContentHost, to fit inner TemplatePart, and for any other features work like default.

simular to example from MSDN:

<Style TargetType="TextBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border CornerRadius="2" Padding="2" Background="#19212F" BorderBrush="Red" BorderThickness="1">
                    <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>