我希望在我的文本框中有一个占位符在wpf ..我试图搜索xaml脚本来解决我的问题,我发现xaml代码对于简单的占位符来说太长了,然后我最终得到了我自己的解决方案..事件处理程序会减慢应用程序的速度吗?
Dim myPlaceholder As String = "My Sample Placeholder"
Private Sub tbStarSign_GotFocus(sender As Object, e As RoutedEventArgs) Handles tbStarSign.GotFocus
If tbStarSign.Text = myPlaceholder Then
tbStarSign.Text = ""
End If
End Sub
Private Sub tbStarSign_LostFocus(sender As Object, e As RoutedEventArgs) Handles tbStarSign.LostFocus
If tbStarSign.Text = "" Then
tbStarSign.Text = myPlaceholder
End If
End Sub
答案 0 :(得分:2)
仅限XAML的解决方案没有任何问题。
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}"
x:Key="TextBoxWithWatermarkStyle">
<Setter Property="Padding" Value="3"/>
<Setter Property="Background" Value="White"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border BorderThickness="1"
CornerRadius="1"
Background="{TemplateBinding Background}">
<Grid>
<ScrollViewer Margin="{TemplateBinding Padding}"
x:Name="PART_ContentHost"/>
<TextBlock IsHitTestVisible="False"
Text="{TemplateBinding Tag}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
Opacity="0.25"
Foreground="{TemplateBinding Foreground}"
Margin="5,0,0,0">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
用法:
<TextBox Style="{StaticResource TextBoxWithWatermarkStyle}" Tag="Hello world" ... />