1. 程式人生 > 實用技巧 >Wpf TextBox 如何簡單粗暴的實現水印效果?

Wpf TextBox 如何簡單粗暴的實現水印效果?

效果圖預覽

新建UserControl

<Border Background="#F3F6F9" Height="50" Width="400"
                    CornerRadius="10" HorizontalAlignment="Stretch"
                    InkCanvas.Left="50">
                <Grid Height="Auto">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <Image Source="/Sample;component/Resources/search.png" Width="25" Stretch="Uniform"/>
                    <TextBox Grid.Column="1" x:Name="searchQuery" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" VerticalContentAlignment="Center" TextAlignment="Left" BorderThickness="0" Background="Transparent"/>
                    <TextBlock Grid.Column="1" Margin="3,0,0,0" Text="請輸入搜尋內容..." FontWeight="Bold" HorizontalAlignment="Left" TextAlignment="Left" VerticalAlignment="Center" Foreground="LightGray" IsHitTestVisible="False">
                        <TextBlock.Style>
                            <Style TargetType="{x:Type TextBlock}">
                                <Setter Property="Visibility" Value="Collapsed"/>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding Text, ElementName=searchQuery}" Value="">
                                        <Setter Property="Visibility" Value="Visible"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>
                </Grid>
            </Border>
search.png 檔案(儲存檔案)