【发布时间】:2016-11-08 18:41:07
【问题描述】:
所以,我有一个名为 WatermarkTextbox 的自定义 WPF 控件,它扩展了 TextBox。我添加到代码中的唯一内容是用于保存水印文本的字符串依赖属性。其余的魔力在 Xaml(如下)中。
<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 设置哪些其他属性才能使其正常工作?
【问题讨论】:
标签: c# wpf xaml custom-controls