WPF: Styled TextBox Not Showing Cursor

时间:2015-05-24 21:26:00

标签: c# wpf xaml styles

I created a style for my textbox, and in order to give it custom border I decided to temper with its ControlTemplate, but when I run the project the cursor does not seem to show in the textbox, why is this and how can I fix it?

The code for my style is below

<Style x:Key="PrimaryTextBox" TargetType="{x:Type TextBox}">
    <Setter Property="BorderBrush" Value="#FFBAC7DC"/>
    <Setter Property="MinHeight" Value="30"/>
    <Setter Property="MinWidth" Value="40"/>
    <Setter Property="BorderBrush" Value="#FF07172B"/>
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="Padding" Value="4"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border CornerRadius="3" Padding="4"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ContentPresenter Content="{TemplateBinding Text}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And its implementation

<TextBox Style="{StaticResource PrimaryTextBox}"/>

1 个答案:

答案 0 :(得分:3)

Since you are replacing the ControlTemplate for the TextBox, you need to make sure you account for all of the features of a TextBox if you want them to work properly. A ContentPresenter with its content set to a string is simply going to render a TextBlock with that text displayed. There is no way to interact with it.

What you want to have instead of a ContentPresenter there is probably this:

<ScrollViewer Name="PART_ContentHost" />

That is the named part where the TextBox implementation is going to place everything. If it cannot find that, then most of its features will not work.

Anytime you are creating your own template for a control, it is a good idea to use a reference to ensure you don't miss anything important. You can find examples for all of the controls on MSDN. In the case of TextBox, you can find the example here: TextBox Styles and Templates