dior001
dior001

Reputation: 761

Control Template TextBox Focus

Apologies if the answer to this question is completely obvious but it has me stumped at the moment. Why will the textboxes in this example not receive focus? If I use vanilla textboxes without the control template the focus works fine.

<StackPanel>
        <Label Name="lblChartTitle"
            Content="{x:Static res:Strings.ChartOptionsTitlesControlView_Label_Title}" />
            <TextBox Name="txtChartTitle" 
                     Text="{Binding Path=ChartTitle}" 
                     MaxLength="255"
                     KeyboardNavigation.TabIndex="1"
                     Template="{DynamicResource ctTextBox3DInset}"
                     />
        <Label Name="lblChartCategoryXAxis"
            Content="{x:Static res:Strings.ChartOptionsTitlesControlView_Label_CategoryXAxis}" />
            <TextBox Name="txtChartCategoryXAxis" 
                     Text="{Binding Path=CategoryXAxis}" 
                     MaxLength="255" 
                     KeyboardNavigation.TabIndex="2"
                     Template="{DynamicResource ctTextBox3DInset}"
                     />
        <Label Name="lblChartValueYAxis"
            Content="{x:Static res:Strings.ChartOptionsTitlesControlView_Label_ValueYAxis}" />
            <TextBox Name="txtChartValueYAxis" 
                     Text="{Binding Path=ValueYAxis}" 
                     MaxLength="255"
                     KeyboardNavigation.TabIndex="3"
                     Template="{DynamicResource ctTextBox3DInset}"
                     />
    </StackPanel>

<ControlTemplate x:Key="ctTextBox3DInset" TargetType="TextBox">
            <Border 
                Style="{StaticResource BorderStyle3DInsetBlack}"
                Margin="0,0,0,5">
                <Border Style="{StaticResource BorderStyle3DInsetWhite}">
                    <Border Style="{StaticResource BorderStyle3DInset}">
                        <TextBox
                            TabIndex="{TemplateBinding TabIndex}"
                            BorderThickness="0"/>
                    </Border>
                </Border>
            </Border>
        </ControlTemplate>

Upvotes: 1

Views: 1044

Answers (1)

King Chan
King Chan

Reputation: 4302

Because when you apply the ControlTemplate, you are actually creates another TextBox.. So the focus is not set to the TextBox within your ControlTemplate.

Edit:

What you need to use is actually <ContentPresenter/>:

<ContentPresenter/>

instead of creating a TextBox using

<TextBox  TabIndex="{TemplateBinding TabIndex}" 
                        BorderThickness="0"/> 

Edit 2: I think my previous answer was wrong, TextBox work differently. You have to use <ScrollViewer Margin="0" x:Name="PART_ContentHost"/> for TextBox, PART_ContentHost is a special name for assign an element as content host. And must be use with ScrollViewer or an AdornerDecorator.

Here is the reference

Upvotes: 1

Related Questions