WPFで雑にウォーターマーク付きのテキストボックスを作る
ウォーターマークのあるテキストボックス(未入力だと透かしがでるやつ)がたまにほしくなりますよね
ガッツリ作る必要もない時はテンプレートで適当に作ってしまえばいいんじゃない?
<Window.Resources> <Style x:Key="WatermarkTextbox" TargetType="{x:Type TextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Grid Background="White"> <ScrollViewer x:Name="PART_ContentHost" Margin="5,0,0,0" VerticalAlignment="Center"/> <TextBlock x:Name="WaterMarkLabel" Text="{TemplateBinding Tag}" Opacity=".5" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5,0,0,0" Visibility="Collapsed"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="Text" Value=""> <Setter Property="Visibility" TargetName="WaterMarkLabel" Value="Visible"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid Background="Blue"> <TextBox Style="{StaticResource WatermarkTextbox}" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Tag="Input please"/> </Grid>
できあがり
TextBox.TagをTextBlock.Textに入れて、TriggerでTextが空白の時に表示しているだけです