【发布时间】:2018-08-24 09:05:14
【问题描述】:
我想扩展一个 TextBox 控件以包含一个 Label,其中 Label 从我的自定义控件的 Label 属性中获取其 Content 并自动附加到 TextBox。 (这是一个用于学习目的的简化示例)。
LabeledTextBox.cs
public class LabeledTextBox : TextBox
{
static LabeledTextBox() =>
DefaultStyleKeyProperty.OverrideMetadata(typeof(LabeledTextBox),
new FrameworkPropertyMetadata(typeof(LabeledTextBox)));
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof(string), typeof(LabeledTextBox));
public string Label
{
get => (string)GetValue(LabelProperty);
set => SetValue(LabelProperty, value);
}
}
主题/Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyExample">
<Style TargetType="{x:Type local:LabeledTextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:LabeledTextBox}">
<StackPanel Orientation="Vertical">
<Label Margin="0 0 0 4" Content="{TemplateBinding Label}" Target="{Binding ElementName=tbThis}" />
<!-- This doesn't work -->
<ContentPresenter x:Name="tbThis" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
我不知道如何显示 TextBox 基类。我搜索了 SO 和 Google 中的前几个链接。看起来我应该使用的是<ContentPresenter />,但它根本没有出现。我还尝试了在 XAML 中设置 ContentPresenter.ContentSource 的几种变体,但均无济于事。
我知道我可以在 ControlTemplate 中添加一个 TextBox,但这意味着要么丢失继承的 TextBox 的所有属性,要么需要手动附加它们,这违背了在 UserControl 上使用自定义控件的全部目的.
【问题讨论】: