【发布时间】:2018-02-01 13:44:11
【问题描述】:
我试图弄清楚如何为我在 UserControl 中的所有文本框定义一个 ControlTemplate,我尝试了几件事,但似乎没有用。
我需要将 KeyBinding 绑定到命令:
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding SaveConfigCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}"/>
</TextBox.InputBindings>
到目前为止,这是可行的,但是将相同的 sn-p 添加到所有文本框并不是一个好习惯。所以我试图把它放在样式上,但我得到 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>
有什么想法吗?提前致谢!
编辑以供将来参考:
虽然答案是正确的,但我想指出 TemplateBinding Text 在控件中已经绑定 Text 属性时是不够的,因为 TemplateBinding 只是一个 OneWay 绑定,你必须使用以下:
Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}"
【问题讨论】: