0

I have a custom textbox that I want to be able to read and write the text from

<Style TargetType="{x:Type TextBox}" x:Key="CustomTextBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border CornerRadius="4"
                        Height="40">
                    <TextBox Background="Transparent"
                             BorderThickness="0"
                             VerticalContentAlignment="Center"
                             FontSize="16"
                             Margin="7,7,7,7"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


<TextBox x:Name="customTextBox" 
         Style="{StaticResource ResourceKey=CustomTextBox}"/>

Then I want to read or write the text like this

customTextBox.Text = "some text here";

In short I basically want to forward a property in a custom control

GHOST
  • 337
  • 3
  • 9
  • There should not be a TextBox in the ControlTemplate of a TextBox. It should instead be ``. See https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/textbox-styles-and-templates. – Clemens Apr 13 '22 at 07:33
  • yea I figured that out a couple hours after I asked this question – GHOST Apr 13 '22 at 18:44

1 Answers1

1

The TextBox that you've added to your template is a different object to the parent object that you're templating, so you need to bind their Text properties together:

<TextBox Background="Transparent"
    BorderThickness="0"
    VerticalContentAlignment="Center"
    FontSize="16"
    Margin="7,7,7,7"
    Text="{Binding Path=Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>

For one-way bindings you can use TemplateBinding, but for two-way bindings like this you need to use RelativeSource.

Mark Feldman
  • 15,731
  • 3
  • 31
  • 58