Forward property in a style

107 Views Asked by At

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

1

There are 1 best solutions below

0
Mark Feldman On

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.