所以,我有一个名为WatermarkTextbox的自定义WPF控件,它扩展了TextBox。我添加到代码中的唯一东西是一个字符串依赖项属性来保存水印文本。其余的魔法在Xaml(下面)。使用自定义WPF控件时无法设置一些属性
<Style TargetType="wpfControls:WatermarkTextbox" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type wpfControls:WatermarkTextbox}">
<Grid>
<TextBox x:Name="baseTextBox" />
<TextBlock Margin="5,0,0,0" x:Name="watermarkText" IsHitTestVisible="False" FontWeight="Light" FontStyle="Italic" Foreground="DarkGray" Visibility="Hidden" Background="Transparent"
Text="{Binding RelativeSource={RelativeSource AncestorType=wpfControls:WatermarkTextbox}, Path=Watermark}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="baseTextBox" Property="Text" Value="">
<Setter TargetName="watermarkText" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
,并在我的应用程序使用时:
<wpfControls:WatermarkTextbox Watermark="Text that disappears."/>
此作品居多。我可以设置水印文本,当我开始输入一些文本时,它会消失。当我更改字体大小时,它会更改水印和我输入的文本;当我改变字体重量时,它只会改变输入的文本(这是我想要的)。我可以改变文本框的大小。这都是肉汁。
问题是,当我开始尝试改变像文本框的背景或边框属性,像这样。
<wpfControls:WatermarkTextbox Watermark="Text that disappears." Background="Yellow"/>
什么也没有发生。与BorderBrush和BorderThickness具有相同的行为。现在,我所知道的部分正好足以让我知道有一些我不知道的重要概念。如果我将我的WatermarkTextbox的模板更改为以下内容,它会让我像我想要的那样在应用程序中设置背景。
<Style TargetType="wpfControls:WatermarkTextbox" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type wpfControls:WatermarkTextbox}">
<Grid>
<TextBox x:Name="baseTextBox"
Background="{TemplateBinding Background}"/>
<TextBlock Margin="5,0,0,0" x:Name="watermarkText" IsHitTestVisible="False" FontWeight="Light" FontStyle="Italic" Foreground="DarkGray"
Text="{Binding RelativeSource={RelativeSource AncestorType=wpfControls:WatermarkTextbox}, Path=Watermark}" Visibility="Hidden" Background="Transparent"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="baseTextBox" Property="Text" Value="">
<Setter TargetName="watermarkText" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我认为如果我为BorderBrush和BorderThickness做了同样的工作,它们也可以工作。
所以,我的问题是,为什么?这些属性使它们的行为与FontSize和FontWeight或Height和Width的行为有什么不同?为什么我必须将背景明确设置为{TemplateBinding Background}而不是FontSize?另外,为了使它们正常工作,还需要将其他属性设置为TemplateBinding?
很好说:“如果设置会给一般的怪异结果,它也可能不会被继承。例如:如果你在网格上设置Margin属性,想象一下每个子元素是否都继承了相同的边距。 –