Reputation: 1691
I'm trying to figure out how to define a ControlTemplate for all the textboxes I have in my UserControl, I have tried several things but doesn't seems to work.
What I need is bind the KeyBinding to a Command:
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SaveConfigCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}"/>
</TextBox.InputBindings>
this is working so far, but adding the same snippet to all the textboxes it's not a good practice. So I tried to put it on the Styles but I get NullReferenceException
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid>
<TextBox Text="{TemplateBinding}"/>
<ContentPresenter>
<ContentPresenter.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SaveConfigCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}"/>
</ContentPresenter.InputBindings>
</ContentPresenter>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
Any ideas? Thanks in advance!
Edit for future references:
Although the answer is correct, I would like to point out that the TemplateBinding Text
it is not enough when you are already binding the Text property in the control, as the TemplateBinding
is only a OneWay
Binding, you have to use the following:
Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}"
Upvotes: 2
Views: 1087
Reputation: 7325
TemplateBinding is used for binding to the control properties within the template definition. Further put your InputBindings to the TextBox.
<Style x:Key="tbxStyle" TargetType="TextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid>
<TextBox Text="{TemplateBinding Text}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SaveConfigCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}"/>
</TextBox.InputBindings>
</TextBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<TextBox Text="{Binding SelectedItem}" Style="{StaticResource tbxStyle}">
Upvotes: 1