Reputation: 61
I'm couple days into learning C# and I just ran into a weird problem. I have a TextBox in WPF application, that normally works without any problem, but after I apply a custom template to it in XAML, it stops returning text value. It is always empty string.
My template in XAML:
<ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBoxBase}">
<Border x:Name="Bd" BorderBrush="DarkGray" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4,4,4,4">
<TextBox Background="#353535" Foreground="White"/>
</Border>
</ControlTemplate>
My TextBox in XAML:
<TextBox x:Name="TextBox" Template="{StaticResource TextBoxBaseControlTemplate}" Foreground="White" BorderThickness="1" BorderBrush="DarkGray" HorizontalAlignment="Stretch" Height="23" Margin="53,0,105,15" TextWrapping="Wrap" Text="Enter city" VerticalAlignment="Bottom" GotFocus="TextBox_GotFocus" KeyDown="TextBox_KeyDown"/>
How can I fix this?
Upvotes: 0
Views: 914
Reputation: 11389
Creating a template includes the need to specify where to find the original properties. Therefore XAML provides the TemplateBinding, which allows to bind the properties of the templated control to the content you are defining.
The obvious solution would be to just use the markup extension to bind the text like:
<TextBox Text="{TemplateBinding Text}" .../>
Unfortunately, this does not work very well in case of a TextBox
like described in
this question. The solution is to bind by relative source like described there. So your template should look like this to provide it's text like expected:
<ControlTemplate x:Key="TextBoxBaseControlTemplate" TargetType="{x:Type TextBox}">
<Border x:Name="Bd" BorderBrush="DarkGray" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4,4,4,4">
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}"
Background="#353535" Foreground="White"/>
</Border>
</ControlTemplate>
Also note, that TextBoxBase
not specifies the Text
property, so templating TextBox
should be prefered here.
Upvotes: 1