我已创建自定义TextBox
,我想为此设置样式,并为此TextBox
添加水印。我希望在TextBox
为空时添加水印,此可见性只能从我的Style
设置。这是我的风格:
<Style TargetType="{x:Type textboxes:CustomTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type textboxes:CustomTextBox}">
<Grid>
<Border Name="Border"
CornerRadius="2"
Padding="2"
Background="DeepPink"
BorderBrush="Green"
BorderThickness="1">
<Grid>
<ScrollViewer Margin="0"
x:Name="PART_ContentHost" />
<TextBlock IsHitTestVisible="False"
Text="WATERMARK!"
Foreground="White"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="10,0,0,0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility"
Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=PART_ContentHost}"
Value="">
<Setter Property="Visibility"
Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style></TextBlock>
</Grid>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
样式按预期应用,但我很难在TextBlock
内定义DataTrigger绑定。我应该绑定什么?
答案 0 :(得分:3)
您应该使用ControlTemplate触发器。您需要检查文本是否为空,但如果文本框没有焦点,则需要多重触发:
这是我的水印文本框样式,我使用Tag属性指定水印文本:
<Style x:Key="WatermarkTextBox" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Tag" Value="Enter Text" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid>
<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>
<TextBlock x:Name="Watermark" Text="{TemplateBinding Tag}"
Visibility="Collapsed" IsHitTestVisible="False" Opacity="0.5"
Foreground="{TemplateBinding Foreground}"
Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"
HorizontalAlignment="Stretch"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextAlignment="{TemplateBinding TextAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsKeyboardFocusWithin" Value="False" />
<Condition Property="Text" Value="" />
</MultiTrigger.Conditions>
<Setter TargetName="Watermark" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>