我正在尝试制作自己版本的控件,比如一个TextBox
,我想要添加一些自定义UI。我想要从这个类中继承,这样用户仍然可以像调用普通文本框一样调用我的特殊文本框。我已经有了以下代码:
// MySpecialTextBox.cs
public class MySpecialTextBox : TextBox
{
static MySpecialTextBox () { }
/* Some special properties */
}
在XAML中:
<Style TargetType="{x:Type MySpecialTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MySpecialTextBox}">
<StackPanel>
<Rectangle Width="100" Height="3" Fill="Pink" /> <!-- My own fancy lay-out -->
<TextBox Text="{TemplateBinding Text}"/> <!-- This text box should 'inherit' ALL the properties from the caller -->
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我的问题是,现在TextBox
只获取您在此模板中明确设置的属性,例如,只有Text
。我还想绑定到Background
、Foreground
和其他可能的属性。显然,我可以这样做:
<ControlTemplate TargetType="{x:Type MySpecialTextBox}">
<StackPanel>
<Rectangle Width="100" Height="3" Fill="Pink" />
<TextBox Text="{TemplateBinding Text}"
Background="{TemplateBinding Background}"
Foreground="{TemplateBinding Foreground}"
AcceptsReturn="{TemplateBinding AcceptsReturn}"
AllowDrop="{TemplateBinding AllowDrop}"
<!-- ETCETERA -->
/>
</StackPanel>
</ControlTemplate>
列出所有属性,但这样做感觉非常低效。有没有一种方法可以一次绑定整个父级元素?