Yel*_*low 6 wpf xaml datatemplate
我正在尝试制作我自己的控件版本,比如 a TextBox,我想向其中添加一些自定义 UI。我想从这个类继承,这样用户仍然可以像调用普通文本框一样调用我的特殊文本框。我有以下几点:
// MySpecialTextBox.cs
public class MySpecialTextBox : TextBox
{
static MySpecialTextBox () { }
/* Some special properties */
}
Run Code Online (Sandbox Code Playgroud)
在 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>
Run Code Online (Sandbox Code Playgroud)
我的问题是,现在,TextBoxonly 获取您在此模板中明确设置的属性,在这种情况下,只有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>
Run Code Online (Sandbox Code Playgroud)
列出所有属性,但这感觉非常低效。有没有办法一次性绑定到整个父级?
TextBox将另一个元素放置在另一个元素的模板中并不是一个好主意TextBox。当您覆盖控件的模板时,您应该做的始终是编辑控件的默认模板。
因此,在 a 的默认模板中,TextBox您将找到以下元素:
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
Run Code Online (Sandbox Code Playgroud)
该边框负责绘制TextBox. 如果你使用这个部分而不是你的内在,TextBox你将拥有所有其他TextBox属性“继承”。
编辑:
完整的模板应该是:
<Style TargetType="{x:Type my:MySpecialTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type my:MySpecialTextBox}">
<StackPanel>
<Rectangle Width="100" Height="3" Fill="Pink" />
<!-- My own fancy lay-out -->
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)